Why does this change two zeroes to 5 instead of just the first one? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why does this change two zeroes to 5 instead of just the first one?

a = [[0]*2]*2 a[0][0] = 5 print(a) #[5,0][5,0]

26th Apr 2019, 5:12 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
2 Answers
+ 5
print(n*list) prints n representations of the same list. Likewise, a = [[0]*2]*2 creates a nested list with two inner lists that are the same. If you change one, you change the other one as well. Use a = [[0 for i in range(2)] for j in range(2)] to create a nested list with two independent inner lists.
26th Apr 2019, 5:41 AM
Anna
Anna - avatar
+ 1
Thanks again! Anna
26th Apr 2019, 6:20 AM
Thimira Rathnayake
Thimira Rathnayake - avatar