Comparing lists in python gets weird
Question:
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?
Answers:
This is odd. It should be working. When making a question, try to provide the simplest working example and the expected output.
By the way, this is not a good way to do list comparison. For the reference, it’s best to use sets comparison, which is much faster.
result = list(set(new)-set(old))
gives you a list of items in new which are absent in old.
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
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?
This is odd. It should be working. When making a question, try to provide the simplest working example and the expected output.
By the way, this is not a good way to do list comparison. For the reference, it’s best to use sets comparison, which is much faster.
result = list(set(new)-set(old))
gives you a list of items in new which are absent in old.
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