Python: check if an item is in two lists?

I need to check if an item is in two lists. I currently have:

if ele not in lista: if ele not in listb: do stuff 

Using the following code did not help. Is there a more efficient way to accomplish the above in python?

 if ele not in lista and listb: do stuff 
+6
source share
3 answers
 if ele not in lista and ele not in listb: # do stuff 

or

 if ele not in lista + listb: # do stuff 

but the second option will include the concatenation of lists, which can cause memory problems with large lists, and also have to go through the list twice. To fix this, you can use itertools :

 from itertools import chain if ele not in chain(lista, listb): # do stuff 

If you are going to constantly check membership, you want to use set , which has O(1) (amortized) search instead of O(n) for lists.

eg.

 items_set = set(chain(lista, listb)) if ele in items_set: # this membership check will be a lot faster # do stuff 
+14
source
 if ele not in lista and ele not in listb: 
+2
source

late, but I just wanted to add some more interesting things

provided that both lists are of equal length

 a = [1,2,3,4,5] b = [6,7,8,9,10] c = all("h" not in pair for pair in zip(a,b)) 

if they have an unequal length:

 from itertools import zip_longest a = [1,2,3,4,5] b = [6,7,8,9,10,11,12,13] c = all("h" not in pair for pair in zip_longest(a,b)) 
0
source

All Articles