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
?
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]
You can also use list comprehension:
C=[i for i in A if i not in B]
Output:
[1, 2, 3]
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]]
set(A).difference(B) # set operation for difference between two collections A and B
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With