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

Comparing lists in python gets weird

The following piece of code removes an element of a list and than compares the two lists and should print the element that was removed (item#1)

old = generateList()  #same list
new = old.copy()      #same list

old.remove("item#1")  #remove one of the items

for item in new:
    if item not in old:
        print(item)

#Expecting: "item#1"
#Getting: Nothing

The problem is that the lists are big (1700+ items) and the code shown above doesn’t work
I tried slicing the list (Made sure the sliced version still had the item (item#1))
With 5 elements the code works.

old = generateList()[0:5]  #same list
new = old.copy()[0:5]      #same list

old.remove("item#1")  #remove one of the items

for item in new:
    if item not in old:
        print(item)

#Expecting: "item#1"
#Getting: "item#1"

Anybody knows what’s going on here?

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 :

My guess: the item you are removing is duplicated.

list.remove removes only the first found item.

Example:

old = ['A', 'B', 'C', 'A']
new = old.copy()

old.remove('A')
# ['B', 'C', 'A']

'A' in old
# True
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