The problem is that you are appending the list as such which is equivalent to appending the reference object to the original list. Therefore, whenever the original list is modified, the changes are reflected in the places where the reference is created, in this case in result
. As you keep iterating via the for loop, all your references appended in result
keep getting updated with the latest value of lst
. The final result is that at the end of the for loop, you have appended 5 references to the original list lst
and all of them store the latest value of lst
being [1,2,3,4,5]
.
There are several ways to avoid this. What you need is to copy only the values. One of them is to use lst[:]
. other way is to use lst.copy()
for item in given:
lst.append(item)
print(lst)
result.append(lst[:])
print (result)
# [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]