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?

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
paper006
  • 19
  • 1
  • 5
  • No. What are you actually trying to do? This might be a variable variables question in disguise, see http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python – timgeb Feb 16 '16 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 – paper006 Feb 16 '16 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. – PM 2Ring Feb 16 '16 at 14:59
  • I appreciate the help. – paper006 Feb 16 '16 at 15:06

3 Answers3

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
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]]
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
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
siphr
  • 421
  • 4
  • 12