Python, compute list difference
If the order does not matter, you can simply calculate the set difference:
>>> set([1,2,3,4]) - set([2,5])
set([1, 4, 3])
>>> set([2,5]) - set([1,2,3,4])
set([5])
Use set
if you don't care about items order or repetition. Use list comprehensions if you do:
>>> def diff(first, second):
second = set(second)
return [item for item in first if item not in second]
>>> diff(A, B)
[1, 3, 4]
>>> diff(B, A)
[5]
>>>
You can do a
list(set(A)-set(B))
and
list(set(B)-set(A))