+ 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?
3 odpowiedzi
+ 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
+ 6
Slick
Ahhg! Thanks a lot. 'Lists are mutable' The key sentence.
A lot of thanks.
+ 5
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥
Thanks a lot, buddy.