lists of variables

Chris Rebert clp2 at rebertia.com
Sat Feb 20 22:34:42 EST 2010


On Sat, Feb 20, 2010 at 7:25 PM, Michael Pardee
<python-list at open-sense.com> wrote:
> 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.

Correct. If you want more gory details, read
http://effbot.org/zone/call-by-object.htm

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

What do you need that functionality for exactly? It's a rather low-level notion.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list