I am trying to append small (num) lists to a final list (lst). The small lists are modified in a loop and at each modification they are appended to the final list. But the result is strange and I did not like the solution. Here is the code.
n = 3
num = []
lst = []
for i in range(n) :
num.append(0)
lst.append(num)
for j in range(n-1) :
for i in range(n) :
num[i] += 1
lst.append(num)
for each in lst :
print each
The result of this code is:
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
However, if instead of using lst.append(num)
, I use lst.append(list(num))
, I get the expected result:
[0, 0, 0]
[1, 0, 0]
[1, 1, 0]
[1, 1, 1]
[2, 1, 1]
[2, 2, 1]
[2, 2, 2]
Is this really the correct way for appending values of a list to another list?
UPDATE:
I see that when I do lst.append(num)
this does not mean that the values of num are appended to lst. It is a reference and because I change the content of num, in the end, all entries of my list lst will reference to the final num. However, if I do this:
lst = []
for i in range(3) :
num = i
lst.append(num)
for each in lst :
print each
I get what is expected, i.e., a list lst with the values [0, 1 , 2]. And in this case, num is changed at every iteration and its final value is num=2.