[0]*2 behaviour | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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]]

24th Jan 2018, 9:56 PM
Алексей Шмуйлович
Алексей Шмуйлович - avatar
2 Answers
+ 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[:]
24th Jan 2018, 11:04 PM
Sebastián Zapata
Sebastián Zapata - avatar
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?
25th Jan 2018, 9:55 PM
Алексей Шмуйлович
Алексей Шмуйлович - avatar