I would like to get the first item from a list matching a condition. It\'s important that the resulting method not process the entire list, which could be quite large. For e
The most efficient way in Python 3 are one of the following (using a similar example):
next(i for i in range(100000000) if i == 1000)
WARNING: The expression works also with Python 2, but in the example is used range
that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use xrange
instead).
Note that the expression avoid to construct a list in the comprehension expression next([i for ...])
, that would cause to create a list with all the elements before filter the elements, and would cause to process the entire options, instead of stop the iteration once i == 1000
.
next(filter(lambda i: i == 1000, range(100000000)))
WARNING: This doesn't work in Python 2, even replacing range
with xrange
due that filter
create a list instead of a iterator (inefficient), and the next
function only works with iterators.
As mentioned in other responses, you must add a extra-parameter to the function next
if you want to avoid an exception raised when the condition is not fulfilled.
next(filter(lambda i: i == 1000, range(100000000)), False)
With this style you need to surround the comprehension expression with ()
to avoid a SyntaxError: Generator expression must be parenthesized if not sole argument
:
next((i for i in range(100000000) if i == 1000), False)