Because when you create a list of lists using [[0]*3]*3
, you're creating one list [0,0,0]
three times, so you'll have [[0,0,0],[0,0,0],[0,0,0]]
, but all of the sub lists ([0,0,0]
) are really refrencing the same list, since you just created one and multiplied it by 3 to create the others, so changing one list will make changes to the other lists.
To prevent this, create independent zero-ed lists using a list comprehension:
s = [[0]*3 for i in range(3)]
i = 0
while i < 3:
j = 0
while j < 3:
print(s[i][j])
s[i][j] += 1
j += 1
i += 1
print(s) # just to see the final result
Which outputs:
0
0
0
0
0
0
0
0
0
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]