Find the first element that meets the condition

Paul Rubin http
Sun Feb 25 12:44:01 EST 2007


"jm.suresh at no.spam.gmail.com" <jm.suresh at gmail.com> writes:
> I have a list and I want to find the first element that meets a
> condition. I do not want to use 'filter', because I want to come out
> of the iteration as soon as the first element is found.
> I have implemented it this way, may be, there should be a built in
> hiding somewhere in the standard libraries?
> 
> def exists(iterable, condition):

To check for existence, use any(condition, iterable).  If you actually
want the first element, use itertools.ifilter(condition, iterable).next().
The suggestion of using dropwhile isn't so great because it actually
consumes the first match, so you have to write your condition to
stop immediately before the element you want, not always easy.



More information about the Python-list mailing list