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]]
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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]]
Method 2
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]]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0