Finding If Any Element In A List Is In Another List And Return The First Element Found
Solution 1:
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
Solution 2:
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:
>>> Noneisnext((element for element in a if element in b_set), None)
True
Solution 3:
do like this:
[e for e in a if e in b]
Solution 4:
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']
Solution 5:
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]
Post a Comment for "Finding If Any Element In A List Is In Another List And Return The First Element Found"