I am trying to find all the elements that are in list A and not in list B.
I thought something like newList = list(set(a) & !set(b))
or newList = list(set(a) & (not set(b)))
would work, but it's not.
If there a better way to achieve what I'm trying to do other than this?
newList = []
for item in a:
if item not in b:
newList.append(item)
Also important, it needs to be done in Python 2.6
You're looking for the set difference:
newList = list(set(a).difference(b))
Alternatively, use the minus operator:
list(set(a) - set(b))
Did you try
list(set(a) - set(b))
Here is a list of all Python set operations.
But this unnecessarily creates a new set for b
. As @phihag mentions, difference
method would prevent this.
If you care about maintaining order:
def list_difference(a, b):
# returns new list of items in a that are not in b
b = set(b)
return [x for x in a if x not in b]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With