x = [8,2,3,4,5]
y = [6,3,7,2,1]
How to find out the first common element in two lists (in this case, \"2\") in a concise and elegant way? Any list
One liner, using next
to take the first item from a generator:
x = [8,2,3,4,5]
y = [6,3,7,2,1]
first = next((a for a in x if a in y), None)
Or more efficiently since set.__contains__
is faster than list.__contains__
:
set_y = set(y)
first = next((a for a in x if a in set_y), None)
Or more efficiently but still in one line (don't do this):
first = next((lambda set_y: a for a in x if a in set_y)(set(y)), None)