Python - eliminates the common elements of two lists

advertisements

If i have two lists:

a = [1,2,1,2,4] and b = [1,2,4]

how do i get

a - b = [1,2,4]

such that one element from b removes only one element from a if that element is present in a.


You can use itertools.zip_longest to zip the lists with different length then use a list comprehension :

>>> from itertools import zip_longest
>>> [i for i,j in izip_longest(a,b) if i!=j]
[1, 2, 4]

Demo:

>>> list(izip_longest(a,b))
[(1, 1), (2, 2), (1, 4), (2, None), (4, None)]