Find first in sequence (simple question)

Steven Bethard steven.bethard at gmail.com
Mon Sep 13 15:57:51 EDT 2004


Neal D. Becker <ndbecker2 <at> verizon.net> writes:

> 
> What is an efficient way to find the first element in a sequence meeting
> some condition?
> 
> For example, the first number > x in a list of numbers.
> 

>>> l = range(20)
>>> def cond(x):
...     return x > 11
...
>>> i = itertools.ifilter(cond, l)
>>> i.next()
12

That is, the first element of the iterator returned by itertools.ifilter 
should be the element you want.

STeve




More information about the Python-list mailing list