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.
How about:
next((e for e in mylist if my_criteria(e)), None)
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"
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