Issue 1722956: x = [[]]*2; x[0].append doesn't work (original) (raw)
This bug is hard to explain in words. It is easiest to just look at the Interactive Python commands issued below.
is assigned a list of two empty lists, however there is something wrong with . is assigned a list of two empty lists using list comprehension. is ok. A check of x == y, shows them equal. However, when trying to append [1,2] to x[0] both x[0] and x[1] are appended to. The same operation on works correctly.
x = [[]]*2 y = [[] for i in range(2)] x == y True x[0].append([1,2]) x [[[1, 2]], [[1, 2]]] y[0].append([1,2]) y [[[1, 2]], []]
I have tested with Python 2.5 and 2.4.
This is not a bug. "x" is a list containing two references to the same list object, while "y" is a list containing references to two distinct list objects.
The "==" operator doesn't test for identity, but compares list contents, which is why it yields True above.
(Please ask any further questions about this behavior on the python-list mailing list.)