Nested Lists Assignment Problem

Fredrik Lundh fredrik at pythonware.com
Wed Apr 26 07:08:32 EDT 2006


"Licheng Fang" wrote:

> But I still wonder why a nested assignment "a = [[0]*3]*3" generates 3
> references to the same list, while the commands below apparently do
> not.

that's because they're replacing a list item, rather than modifying it.

>>>> a = [0] * 2
>>>> a
> [0, 0] <- now you have two references to the same integer.
>>>> a[0] = 1 <- now you've *replaced* the first integer with another integer.
>>>> a
> [1, 0]

if you do the same thing with lists, it behaves in exactly the same way:

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] <-- three references to the same list
>>> a[0] = [1, 2, 3] <-- replace the first list
>>> a
[[1, 2, 3], [0, 0, 0], [0, 0, 0]]

however, if you modify the *shared* object, the modification will of course
be visible everywhere that object is used:

>>> a[1][0] = "hello" <-- modified the first item in the shared list
>>> a
[[1, 2, 3], ['hello', 0, 0], ['hello', 0, 0]]

</F> 






More information about the Python-list mailing list