0
Appending list to another list in range
Hi, I don't understand the output of this code: L = [] D = [] for x in range (4): D.append(x) L.append(D) print(L) print(D) I assumed that the output will be: [[0], [0,1], [0,1,2], [0,1,2,3]] [0,1,2,3] The actual output is: [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] [0, 1, 2, 3] For me is clear that D = [0,1,2,3], but L is hard to understand.
2 odpowiedzi
0
D = something different at each iteration. 0, 01, 012, 0123.
L goes through iteration also.
0
01,01
012,012,012
0123,0123,0123,0123
After the final iteration that's what you have.
0
How should I change the code so that L = [[0], [0,1], [0,1,2], [0,1,2,3]]?
I still don't fully understand this. I thought that the function append adds an element only once but here it is addes 4 times at the final iteration?