How to check if an item from list A is in list B in Python?

If I have one element one, 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 need to check if there are items in list A in list B ?

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

How do I get a result showing that 1 , 2 , 3 not on list B ?

+6
source share
6 answers

List Usage:

true answer

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

list of items not in the second list

 [x for x in [1, 2, 3, 4] if x not in [4, 5, 6, 7]] 
+1
source

if the items in the list are hashed:

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

otherwise you can use filter :

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

in this case, if sorting is B , you can get better performance using bisect.bisect_left to search by logarithm:

 >>> 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] 
+4
source

You can also use list comprehension:

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

Output:

 [1, 2, 3] 
+3
source

You can use set .

eg.

 >>> a=[1,2,3,4] >>> b=[4,5,6,7] >>> list(set(a)-set(b)) [1, 2, 3] >>> 
+1
source
 set(A).difference(B) # set operation for difference between two collections A and B 
+1
source

This is 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]) 
0
source

Source: https://habr.com/ru/post/989274/


All Articles