0 votes
1 view
in Python by (47.8k points)

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 example, the following function is adequate:

def first(the_iterable, condition = lambda x: True):

for i in the_iterable:

if condition(i):

return i

This function could be used something like this:

>>> first(range(10))


>>> first(range(10), lambda i: i > 3)


However, I can't think of a good built-in/one-liner to let me do this. I don't particularly want to copy this function around if I don't have to. Is there a built-in way to get the first item matching a condition?

1 Answer

0 votes
by (107k points)

If you want to get the first item from an iterable that matches a condition you can use the StopIteration it will raise an error if no matching element is found:

next(x for x in the_iterable if x > 3)

When you deal with Python 2.5, the .next() method of iterators immediately raises StopIteration if the iterator immediately finishes -- i.e., for your use case, if no item in the iterable satisfies the condition. If you don't care (i.e., you know there must be at least one satisfactory item) then just use .next() (best on a genexp, line for the next built-in in Python 2.6 and better.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !