lists of variables

Michael Pardee python-list at
Sun Feb 21 04:25:19 CET 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:

>>> 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

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"

More information about the Python-list mailing list