Find first in sequence (simple question)

Alex Martelli aleaxit at yahoo.com
Tue Sep 14 10:50:26 EDT 2004


Neal D. Becker <ndbecker2 at verizon.net> wrote:
   ...
> I really was looking for a more general "find_first" function, that would
> find the first occurance in a sequence meeting some predicate, with
> short-circuit evaluation (not evaluating the function for every element
> first).

Steven Bethard's suggestion does generalize nicely:

def find_first(seq, pred):
    return itertools.ifilter(pred, seq).next()

This gives you the first _item_ in seq that satisfies pred (or raises
StopIteration if none does -- it's easy to wrap a try/except around the
return statement to change exception, return a default value, whatever).

If you want the _index_ of that first item it's a bit worse...:

def find_first_index(seq, pred):
    def aux_pred((index, item)): return pred(item)
    return itertools.ifilter(aux_pred, enumerate(seq)).next()[0]


Alex



More information about the Python-list mailing list