I have two lists, for example:
a = ["mail1", "mail2", "mail3", "mail4"]
b = ["mail2", "mail5"]
and I want to check if any of the elements in list b
also appears in list a
.
I wanted to know if there is a way (and what is it) to do this without a for loop.
Also I wanted to know how can I create a list of boolean values, where each value will be the result of the comparison of values a[i]
and b[i]
, something like:
[z for i, j in zip(a, b) z = i == j] # (just with the right syntax)
z
will be 1
if in some place i == j
, so I can check the array for any 'True' values.
You can use any
:
any(x in a for x in b)
The nice thing about this generator expression is that any
will return True
as soon as the generator yields a True
, i.e. there won't be redundant x in a
lookups.
Edit:
You can improve the time complexity by making a set from a
.
a_set = set(a)
any(x in a_set for x in b)
Regarding your new question:
[x == y for x,y in zip(a,b)]
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