Home > Back-end >  Comparing lists in python gets weird
Comparing lists in python gets weird

Time:08-18

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?

CodePudding user response:

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
  • Related