12

If I have one element alone this is easy:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

But what if I have two lists and have to check if the elements in list A occur in list B?

A=[1,2,3,4]
B=[4,5,6,7]

How do I get a results showing me that 1,2,3 are not in list B?

Alexander
  • 23,432
  • 11
  • 63
  • 73
Robert Buckley
  • 11,196
  • 6
  • 24
  • 25
  • possible duplicate of [Finding elements not in a list](http://stackoverflow.com/questions/2104305/finding-elements-not-in-a-list) – Eli Korvigo Jun 17 '15 at 11:55

6 Answers6

7

if the items in the list are hashable:

>>> set(A) - set(B)
{1, 2, 3}

otherwise, you may use filter function:

>>> list(filter(lambda a: a not in B, A))
[1, 2, 3]

in that case, if B is sorted, you may get a better performance by using bisect.bisect_left to search logarithmically:

>>> def pred(a):  # if B is already *sorted*
...     from bisect import bisect_left
...     i = bisect_left(B, a)
...     return i == len(B) or B[i] != a
... 
>>> list(filter(pred, A))
[1, 2, 3]
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
6

You can also use list comprehension:

C=[i for i in A if i not in B]

Output:

[1, 2, 3]
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
3

Using list comprehension:

truthy answer

any([True for x in [1, 2, 3, 4] if x in [4, 5, 6, 7]])

list of elements not present in the second list

[x for x in [1, 2, 3, 4] if x not in [4, 5, 6, 7]]
zxzak
  • 8,985
  • 4
  • 27
  • 25
2
set(A).difference(B) # set operation for difference between two collections A and B
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • Just to point out that this is not the symmetric difference. `set(A).difference(B)` will yield a different result than `set(B).difference(A)` when the lists are not exactly equal. If B contains a subset of A, then the latter will result an empty set. `set(A).symmetric_difference(B)` yields the same as `set(B).symmetric_difference(A)`. Here is a good link: https://www.programiz.com/python-programming/methods/set/difference – Daniel F Sep 23 '18 at 18:45
1

That's a typical case for boolean operations on sets:

zerotonine = set(range(10))
fourtoten = set(range(4,11))
print "exclusively in one:", zerotonine ^ fourtoten
exclusively in one: set([0, 1, 2, 3, 10])
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • 1
    Just to point out: This is the same as using `set(A).symmetric_difference(B)` which has the same result as `set(B).symmetric_difference(A)`. Be aware that `set(A).difference(B)` could return a different result than `set(B).difference(A)` ("In A but not in B" vs "In B but not in A"), in case you're after such a property (as the question's title might suggest) – Daniel F Sep 23 '18 at 18:49
0

You can use set.

e.g.

>>> a=[1,2,3,4]
>>> b=[4,5,6,7]
>>> list(set(a)-set(b))
[1, 2, 3]
>>>
shantanoo
  • 3,617
  • 1
  • 24
  • 37