Anar Abiyev
Anar Abiyev

Reputation: 33

Python - Append list to list

I am trying to solve a problem about lists. For output I want to add all the lists to one final list (ans).

But when I append the second list, the first list becomes equal to the second one. I can't understand why this happens.

ls = list()     
ans = []
n = int(input())

for _ in range(n):

    cmd = input()
    if cmd == "insert":
        i, e = map(int, input().split())
        ls.insert(i, e)
    elif cmd == "print":
        ans.append(ls)

    elif cmd == "remove":
        e = int(input())
        ls.remove(e)
    elif cmd =="append":
        e = int(input())
        ls.append(e)
    elif cmd == "sort":
        ls.sort()
    elif cmd == "pop":
        ls.pop()
    elif cmd == "reverse":
        ls.reverse()
    else:
        print("invalid input") 


print(ans)      

Input:

12
insert
0 5
insert
1 10
insert
0 6
print
remove
6
append
9
append
1
sort
print
pop
reverse
print

Upvotes: 0

Views: 742

Answers (1)

Yosua
Yosua

Reputation: 421

When you append a list into a list, i.e. ans.append(ls) you actually pass it by reference. So when you append ls 3 times into ans it will append the same reference of ls.

If you don't want to append by reference, you should give a copy of the list. And in a more complicated list you probably should do deep copy.

Here is to append a copy:

ans.append(ls.copy())

Hope it helps!

Upvotes: 1

Related Questions