1

While creating a quiz game I came across this weird discovery, when using .pop() method on a list that is a copy of another list, the original list's items are removed. I wrote this simple code to let you better understand what I mean:

myList = [1, 2, 3, 4]
myListDup = myList
print("{}\n{}".format(myListDup, myList))

for i in range(len(myList)):
    myListDup.pop()

print("{}\n{}".format(myListDup, myList))

As this shows, after using .pop() to remove all the elements from myListDup, myList is empty aswell (I know there are other ways to remove elements, but I need to use .pop() in my original program) Are there ways to avoid this?

3 Answers3

2

When you are doing myListDup = myList this is just creating another reference myListDup to the original list myList.

Try this:

myListDup = list(myList)

or

myListDup = myList[:]

This will create a new copy of the list and then assign it to myListDup

SigKill
  • 87
  • 5
0

Use copy(),

myList = [1, 2, 3, 4]
myListDup = myList.copy()
print("{}\n{}".format(myListDup, myList))

for i in range(len(myList)):
    myListDup.pop()

print("{}\n{}".format(myListDup, myList))
QuantumX
  • 118
  • 9
0

You can use the list copy method for copying the list

Like,

mylist = [1, 2, 3, 4]
copy_list = my_list.copy()
my_list.pop()
print(my_list)
print(copy_list)

Output

[1,2,3]
[1,2,3,4]
sourin_karmakar
  • 389
  • 3
  • 10