Nested loop and appending hierarchical list

i am running a code given below

lst1 = []

lst2 = []

for i in range(2):

    lst1.append(i)

    for j in range(3):

        lst2.append(lst1)

i expected that
lst1 = [0,1] at the end of program, and
lst2 = [[0], [0], [0], [0,1], [0,1], [0,1]]

but got lst2 = [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]

can anyone explain me why lst2 is like that

The problem can be summarized like this:

>>> lst1 = []
>>> lst2 = [lst1]
>>> lst1.append(42)
>>> lst2
[[42]]

What’s going on? lst2 contains lst1, which is being modified. Inside lst2, there is the underlying lst1 object, which is mutable. When you mutate it, with append(), you’re doing nothing to lst2, but it changes appearance because what’s inside has changed.

You probably want distinct lists. In that case, you can use the copy() method of list objects, which constructs a new list with the same elements. The difference with the original list is that if you change the original, the new list doesn’t change, it is independent.

lst1 = []
lst2 = []
for i in range(2):
    lst1.append(i)
    for j in range(3):
        lst2.append(lst1.copy())

This article has some details:

1 Like

thanks @jeanas, i was thinking something like that. Now it is clear. thanks once again

What Jean Abou Samra said is correct, and very good advice. The only
thing I would say is that instead of using the copy method it is more
Pythonic and slightly faster to use slicing to make the copy:

lst2.append(lst1.copy())

lst2.append(lst1[:])  # use slicing instead
3 Likes