trouble with lists

Bill Mill bill.mill at gmail.com
Tue May 3 14:02:46 EDT 2005


On 3 May 2005 10:42:43 -0700, anandr86 at gmail.com <anandr86 at gmail.com> wrote:
> I'm new to python. I tried doing this
> 
> >>> x = [[]] * 3
> >>> print x
> [ [] [] [] ]
> >>> x[0].append( 2 )
> [ [2] [2] [2] ]
> 
> I confused with the last line output. I actually expected something
> like
> 
> [ [2] [] [] ]
> 
> Can anyone give me an explanation. help!!
> 

All three lists refer to the same object:

>>> x = [[]]*3
>>> x
[[], [], []]
>>> #the id function returns the memory address of an object
...
>>> [id(a) for a in x]
[168612012, 168612012, 168612012]

So, when you change the first object, you change all of them. This is
a common gotcha with mutable objects (lists and dictionaries, mostly).
To get three independant lists, try a list comprehension:

>>> y = [[] for i in range(3)]
>>> y
[[], [], []]
>>> [id(b) for b in y]
[168611980, 168612300, 168611916]

Or, replace x[0] with a new list, instead of modifying the one already there:

>>> x[0] = [2]
>>> x
[[2], [], []]

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list