It is easy to check if an element of a list is in another list using any()
:
any(elem in list2 for elem in list1)
but is there
def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
This answer is similar to an answer on a similar question, where @jamylak goes into more detail of timing the results compared to other algorithms.
If you just want the first element that matches, use next:
>>> a = [1, 2, 3, 4, 5]
>>> b = [14, 17, 9, 3, 8]
>>> next(element for element in a if element in b)
3
This isn't too efficient as it performs a linear search of b
for each element. You could create a set
from b
which has better lookup performance:
>>> b_set = set(b)
>>> next(element for element in a if element in b_set)
If next
doesn't find anything it raises an exception:
>>> a = [4, 5]
>>> next(element for element in a if element in b_set)
Traceback (most recent call last):
StopIteration
You can give it a default to return instead, e.g. None
. However this changes the syntax of how the function parameters are parsed and you have to explicitly create a generator expression:
>>> None is next((element for element in a if element in b_set), None)
True
do like this:
[e for e in a if e in b]
Use sets: https://docs.python.org/2/library/sets.html
result = set(list1) & set(list2)
if you want to make it a conditional like any:
if (set(list1) & set(list2)):
do something
Yes, it is possible, by using a filter when doing your list comprehension :
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['g', 'z', 'b', 'd', '33']
[elem for elem in list1 if elem in list2]
# ['b', 'd']
Use a list comprehension:
[elem for elem in list1 if elem in list2]
Example:
list1 = [1, 2, 3, 4, 5]
list2 = [1, 10, 2, 20]
c = [elem for elem in list1 if elem in list2]
print(c)
Output
[1, 2]