Question on loops and append method. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Question on loops and append method.

L, D = [], [] for i in range(3): D.append(i) L.append(D) print(L) output : [[0,1,2],[0,1,2],[0,1,2]] I thought the output is [[0],[0,1],[0,1,2]] Can anyone please explain me this?

4th May 2020, 12:13 PM
M Tamim
M Tamim - avatar
3 Answers
+ 2
Because lists are mutable. Every time you append to D you are effectivly changing EVERY occurence of D. What youre doing works, you can test it by printing L INSIDE the for loop. At the end, L contains 3 lists (D) with all the same values, wich is why its all the same
4th May 2020, 12:22 PM
Slick
Slick - avatar
+ 6
Slick Ahhg! Thanks a lot. 'Lists are mutable' The key sentence. A lot of thanks.
4th May 2020, 12:57 PM
M Tamim
M Tamim - avatar
4th May 2020, 12:59 PM
M Tamim
M Tamim - avatar