Possible Duplicate:
Python list subtraction operation
In Python you can concatenate lists like so:
print([3,4,5]+[4,5])
which gives this output:
[3,4,5,4,5]
But what I’m looking for is an equivalent ‘subtraction’ operation, so that doing something like this:
print([3,4,5]-[4,5])
Will output this:
[3]
However, the subtraction operator isn’t defined for lists. I’ve tried this:
a = [3,4,5]
b = [4,5]
print(list(filter(lambda x : x not in b,a)))
Which works, but I’m uncertain whether or not this is the best way to do this. I would also like to preserve the original item positions
You can easily do this with a list comprehension:
nl = [elem for elem in a if elem not in b]Edit
Better to use a
setto test against. This will remove duplicates from your list.