I need to check if an element is not in two lists. I currently have:
if ele not in lista: if ele not in listb: do stuffUsing the following code did not work. Is there a more efficient way to accomplish the above in python?
if ele not in lista and listb: do stuff 3 Answers
if ele not in lista and ele not in listb: # do stuffor
if ele not in lista + listb: # do stuffbut the second option will involve list concatenation which could potentially cause memory issues with large lists, also it will have to go through the list twice. To remedy this you could use itertools:
from itertools import chain
if ele not in chain(lista, listb): # do stuffIf you are going to be constantly checking for membership, you want to be using a set which has O(1) (amortized) lookup 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 2 if ele not in lista and ele not in listb: late but I just wanted to add some more cool stuff
assuming 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 are of 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))