Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 729
Robert Buckley Avatar asked Jun 17 '15 11:06

Robert Buckley


5 Answers

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]
like image 60
behzad.nouri Avatar answered Oct 02 '22 15:10

behzad.nouri


You can also use list comprehension:

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

Output:

[1, 2, 3]
like image 27
Joe T. Boka Avatar answered Oct 02 '22 15:10

Joe T. Boka


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]]
like image 41
zxzak Avatar answered Oct 02 '22 13:10

zxzak


set(A).difference(B) # set operation for difference between two collections A and B
like image 37
Malik Brahimi Avatar answered Oct 02 '22 15:10

Malik Brahimi


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])
like image 41
Marcus Müller Avatar answered Oct 02 '22 15:10

Marcus Müller