Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.pop() removes elements from original list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading