0

I don't know if it is possible in Python but here is what I intend to do

var = 5
array=[]
array.append(var)
array[0] = 1

I want var and array[0] to be updated with 1 and print 1:

print(array[0])
print(var)

Is it possible in Python to send in a pointer and dereference the pointer value to change it?

4
  • No. What are you actually trying to do? This might be a variable variables question in disguise, see stackoverflow.com/questions/1373164/… Commented Feb 16, 2016 at 14:44
  • @timgeb That will work. With a dictionary this will work, because I just wanted to give the value a name(meaning). Thanks Commented Feb 16, 2016 at 14:46
  • 1
    BTW, array is not a great name for a list because it's the name of the standard Python module that defines actual arrays. Commented Feb 16, 2016 at 14:59
  • I appreciate the help. Commented Feb 16, 2016 at 15:06

3 Answers 3

2

Python doesn't really have variables*, Python has names. See Facts and myths about Python names and values by Ned Batchelder.

Therefore, C-like concepts of pointers don't translate well to Python. var is just a name that points to the integer object 5; by appending var to array, you created another reference to that object, not a pointer to var.

Whatever you're trying to do might be better serviced by, for example, a dictionary:

vars = {"var": 5}
array = []
array.append("var")
vars[array[0]] = 1

print(vars[array[0]]) # prints "1"
print(vars["var"])    # ditto

*In the abovementioned article, Ned Batchelder writes that "names are Python's variables". In other words, Python does have variables, but they work in a different way than variables in, say, C or Java.

Sign up to request clarification or add additional context in comments.

Comments

1

It is not possible in python. (list is mutable but integer is immutable) You can use aliasing of mutable objects to achieve a similar effect.

So you can do like this,

>>> var = [5]
>>> array = []
>>> array.append(var)
>>> var[0] = 3
>>> array
[[3]]

Comments

0

I think this could also work for you:

val=[]
array=val
array.append(5)

# it is all aliased so everything should be equal
print val[0], array[0], val == array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.