python - Finding if any element in a list is in another list and return the first element found -
it easy check if element of list in list using any()
:
any(elem in list2 elem in list1)
but there anyway idiomatic way return first element found?
i'd prefer one-line solution rather than:
for elem in list1: if elem in list2: return elem
this answer similar an answer on a similar question, @jamylak goes more detail of timing results compared other algorithms.
if want first element matches, use next
:
>>> = [1, 2, 3, 4, 5] >>> b = [14, 17, 9, 3, 8] >>> next(element element in if element in b) 3
this isn't efficient performs linear search of b
each element. create set
b
has better lookup performance:
>>> b_set = set(b) >>> next(element element in if element in b_set)
if next
doesn't find raises exception:
>>> = [4, 5] >>> next(element element in if element in b_set) traceback (most recent call last): stopiteration
you can give default return instead, e.g. none
. changes syntax of how function parameters parsed , have explicitly create generator expression:
>>> none next((element element in if element in b_set), none) true
Comments
Post a Comment