Python list problem [duplicate]

python:

m=[[0]*3]*2
for i in range(3):
    m[0][i]=1

print m

I expect that this code should print

[[1, 1, 1], [0, 0, 0]]

but it prints

[[1, 1, 1], [1, 1, 1]] 

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]]

This is a bit devilish, but quite obvious when you understand what you're doing. when you're doing the [[0]*3]*2 bit, you're first creating a list with 3 zeros, then you copy that to make two elements. But when you do that copy, you do not create new lists with the same contents, but rather reference the same list several times. So when you change one, they all change.

An example to highlight it:

In [49]: s = [[]]*2 # Create two empty lists

In [50]: s # See: 
Out[50]: [[], []]

In [51]: s[0].append(2) # Alter the first element (or so we think)

In [52]: s # OH MY, they both changed! (because they're the same list!)
Out[52]: [[2], [2]]