简体   繁体   中英

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

When you append a list into a list, ie 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM