Not sure if this is a bug, cannot find any clarification in the documentation. Please reassign it if need be.
Using the * operator to generate a list of lists:
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
gives a list of 3 lists of zeroes, as expected.
But the data values appear to be shared, so e.g.
>>> a[1][1] = 'spam'
>>> a
[[0, 'spam', 0], [0, 'spam', 0], [0, 'spam', 0]]
Not what I was expecting!
A list comprehension gives the results I wanted:
>>> a = [[0 for x in range(3)] for x in range(3)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Looks just the same, but:
>>> a[1][1] = 'spam'
>>> a
[[0, 0, 0], [0, 'spam', 0], [0, 0, 0]]
gives a different result, and is actually what I was expecting from the first example. |