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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With