Yugo Kamo Yugo Kamo - 4 months ago 6
Python Question

Nested List and For Loop

Consider this:

list = 2*[2*[0]]
for y in range(0,2):
for x in range(0,2):
if x ==0:
list[x][y]=1
else:
list[x][y]=2
print list


Result:

[[2,2],[2,2]]


Why doesn't the result be [[1,1],[2,2]]?

Answer

Because you are creating a list that is two references to the same sublist

>>> L = 2*[2*[0]]
>>> id(L[0])
3078300332L
>>> id(L[1])
3078300332L

so changes to L[0] will affect L[1] because they are the same list

The usual way to do what you want would be

>>> L = [[0]*2 for x in range(2)]
>>> id(L[0])
3078302124L
>>> id(L[1])
3078302220L

notice that L[0] and L[1] are now distinct