Python list problem [duplicate]

This is by design. When you use multiplication on elements of a list, you are reproducing the references.

See the section “List creation shortcuts” on the Python Programming/Lists wikibook which goes into detail on the issues with list references to mutable objects.

Their recommended workaround is a list comprehension:

>>> s = [[0]*3 for i in range(2)]
>>> s
[[0, 0, 0], [0, 0, 0]]
>>> s[0][1] = 1
>>> s
[[0, 1, 0], [0, 0, 0]]

Leave a Comment