Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if two lists share at least one element [duplicate]

Tags:

python

list

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.

like image 266
Yarden Avatar asked Dec 01 '22 19:12

Yarden


1 Answers

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)]
like image 109
timgeb Avatar answered Dec 07 '22 22:12

timgeb