Incerteza
Incerteza

Reputation: 34884

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.

Upvotes: 7

Views: 4451

Answers (1)

vaultah
vaultah

Reputation: 46533

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.

Upvotes: 18

Related Questions