lists of variables

bartc bartc at freeuk.com
Sun Feb 21 16:54:30 EST 2010


"Michael Pardee" <python-list at open-sense.com> wrote in message 
news:mailman.22.1266722722.4577.python-list at python.org...
> 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

That shows a different outlook. I would have said your first example works 
as expected and it was the second example that was strange, possibly due to 
shallow instead of deep copies by Python.

-- 
Bartc 




More information about the Python-list mailing list