Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the first element or None from filter

Is there a convenient way to return the first element or None from filter?

filter(lambda x: x == 5, [3, 5, 5, 8]) # ?? 5
filter(lambda x: x == 35, [3, 5, 5, 8]) # ?? None

instead of having to call list() and then [0]?

My question is about the method filter and not list comprehension.

like image 477
Incerteza Avatar asked Dec 18 '22 21:12

Incerteza


1 Answers

filter objects are essentially iterators. Just use the next function to get the first value:

next(filter(lambda x: x == 35, [3, 5, 5, 8]), None)

next(it, None) will return None if next(it) raises StopIteration.

like image 98
vaultah Avatar answered Feb 14 '23 07:02

vaultah