+ 1
[0]*2 behaviour
Explain, please, why this code returns this result? Why 5 appear in the second list too? a=[[0]*2]*2 a[0][0]=5 print(a) >>[[5, 0], [5, 0]]
2 Réponses
+ 3
Because "a" has two lists as elements, but the second list is a copy of the first. Both share the same memory allocation, so if you modify any of them, the other will be modified too.
a = [1,2,3]
b = a
b[1] = 4
print(a) , it outputs: [4,2,3]
Then if you want to prevent this, you can write:
b = a[:]
0
But first element of "a" has two elements too. End second element is a copy of the first. Why did it not modify each other?