Find first in sequence (simple question)
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Sep 13 16:38:51 EDT 2004
Neal D. Becker wrote:
> 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.
>
>
for element in sequence:
if element > x:
break
else:
raise ValueError, 'nothing in %r > %r' % (sequence, x)
# Now element is the first such element.
If you need to get the index:
for index, element in enumerate(sequence):
if element > x:
break
else:
raise ValueError, 'nothing in %r > %r' % (sequence, x)
# Now element is the first such element (sequence[index]).
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list