List weirdness - what the heck is going on here?

alex23 wuwei23 at gmail.com
Thu Jan 28 03:59:26 CET 2010


Rotwang <sg... at hotmail.co.uk> wrote:
> Can anybody tell me what's going on?

Your problem is basically this:

>>> a = [1]
>>> b = [a] * 2
>>> b
[[1], [1]]
>>> a.append(2)
>>> b
[[1, 2], [1, 2]]

The expression '[a] * 2' doesn't make two copies of list of a list of
a, it makes two nested _references_ to it. When you modify the 'first'
list, you're seeing that changed reflected in the second reference.

The list comprehension, however, is returning a _new_ list each time.
Changing its contents doesn't affect any of the other independently
created lists.



More information about the Python-list mailing list