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

Removing item from list in for loop removes from both lists

list1 = [1, 2, 3]
list2 = list1

for i, x in enumerate(list2):
    print(list1, list2)
    del list2[i]

returns

[1, 2, 3] [1, 2, 3]
[2, 3] [2, 3]
[2] [2]

when I expect it to return

[1, 2, 3] [1, 2, 3]
[1, 2, 3] [2, 3]
[1, 2, 3] [2]

I am new to python and was wondering if I am doing something wrong or missing something.

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

edit:

list1 = [1, 2, 3]
list2 = list1.copy()

for i in list1:
    print(list1, list2)
    list2.remove(i)

fixed it

>Solution :

If you want to solve this, you need to create a copy of x into a new item which can be done with the copy module

from copy import copy

list1 = [1, 2, 3]
list2 = copy(list1)

for i, x in enumerate(list2):
    print(list1, list2)
    del list2[i]
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