2

I want to intersect two lists (with NOT), and return the elements of list A that are not present in list B.

example:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) ????? set(b))
[2, 4]
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
fj123x
  • 6,904
  • 12
  • 46
  • 58

3 Answers3

7

You are looking for the set difference; the - operator will do that for you:

list(set(a) - set(b))

If you use the set.difference() method the second operand does not need to be a set, it can be any iterable:

list(set(a).difference(b))

Demo:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a).difference(b))
[2, 4]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Something like this?

>>> list(set(a) - set(b))
[2, 4]
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
3
a = [1,2,3,4,5]
b = [1,3,5,6]
print list(set(a) - set(b))
badc0re
  • 3,333
  • 6
  • 30
  • 46