1

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.

hmm
  • 37
  • 8

2 Answers2

1

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)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0
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

Community
  • 1
  • 1
satikin
  • 3
  • 3
  • You could do `set(a) - set(b)`, but this will also remove all the duplicates and scramble up the order, which might not be intended. – tobias_k Apr 01 '15 at 11:35