lists of variables

Michael Pardee python-list at open-sense.com
Sat Feb 20 22:25:19 EST 2010


I'm relatively new to python and I was very surprised by the following behavior:

>>> a=1
>>> b=2
>>> mylist=[a,b]
>>> print mylist
[1, 2]
>>> a=3
>>> print mylist
[1, 2]

Whoah!  Are python lists only for literals?  Nope:

>>> c={}
>>> d={}
>>> mydlist=[c,d]
>>> print mydlist
[{}, {}]
>>> c['x']=1
>>> print mydlist
[{'x': 1}, {}]

So it looks like variables in a list are stored as object references.
This seems to confirm that:

mydlist[1]['y']=4
>>> print mydlist
[{}, {'y': 4}]

So I figure my initial example doesn't work because if you assign a
literal to something it is changing the object.  But modifying a list
or dict (as long as you don't re-construct it) does not change the
object.

I can think of some ways to work around this, including using single
element lists as "pointers":

>>> aa=[1]
>>> bb=[2]
>>> myplist=[aa,bb]
>>> print myplist
[[1], [2]]
>>> aa[0]=3
>>> print myplist
[[3], [2]]


But what would be "the python way" to accomplish "list of variables"
functionality?



More information about the Python-list mailing list