Robert Buckley
Robert Buckley

Reputation: 11926

How to check if an element from List A is not present in List B in Python?

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?

Upvotes: 15

Views: 34849

Answers (6)

Malik Brahimi
Malik Brahimi

Reputation: 16711

set(A).difference(B) # set operation for difference between two collections A and B

Upvotes: 3

behzad.nouri
behzad.nouri

Reputation: 77951

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]

Upvotes: 10

zxzak
zxzak

Reputation: 9446

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

Upvotes: 4

Joe T. Boka
Joe T. Boka

Reputation: 6581

You can also use list comprehension:

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

Output:

[1, 2, 3]

Upvotes: 7

shantanoo
shantanoo

Reputation: 3704

You can use set.

e.g.

>>> a=[1,2,3,4]
>>> b=[4,5,6,7]
>>> list(set(a)-set(b))
[1, 2, 3]
>>>

Upvotes: 0

Marcus Müller
Marcus Müller

Reputation: 36352

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

Upvotes: 1

Related Questions