hmm
hmm

Reputation: 47

Python - eliminating common elements from two lists

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.

Upvotes: 1

Views: 172

Answers (2)

satikin
satikin

Reputation: 3

a = [1,2,1,2,4] 
b = [1,2,4]
c= set(a) & set(b)
d=list(c)

The answer is just a little modification to this topic's answer: Find non-common elements in lists

and since you cannot iterate a set object: https://www.daniweb.com/software-development/python/threads/462906/typeerror-set-object-does-not-support-indexing

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

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)]

Upvotes: 1

Related Questions