Alex Rivera | Logout

Python list problem

Asked 2009-12-24T20:57:24.613
9

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

1 Answer

18

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]]
answered 2009-12-24T21:02:00.847

Your Answer