Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the first list element for which a condition is true [duplicate]

I was looking for an elegant (short!) way to return the first element of a list that matches a certain criteria without necessarily having to evaluate the criteria for every element of the list. Eventually I came up with:

(e for e in mylist if my_criteria(e)).next()

Is there a better way to do it?

To be more precise: There's built in python functions such as all() and any() - wouldn't it make sense to have something like first() too? For some reason I dislike the call to next() in my solution.

like image 423
Alexander Tobias Bockstaller Avatar asked Jun 06 '13 13:06

Alexander Tobias Bockstaller


2 Answers

How about:

next((e for e in mylist if my_criteria(e)), None)
like image 180
iruvar Avatar answered Nov 09 '22 03:11

iruvar


Nope - looks fine. I would be tempted to re-write possibly as:

from itertools import ifilter
next(ifilter(my_criteria, e))

Or at least break out the computation into a generator, and then use that:

blah = (my_function(e) for e in whatever)
next(blah) # possibly use a default value

Another approach, if you don't like next:

from itertools import islice
val, = islice(blah, 1)

That'll give you a ValueError as an exception if it's "empty"

like image 26
Jon Clements Avatar answered Nov 09 '22 03:11

Jon Clements