Find first in sequence (simple question)

N

Neal D. Becker

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

Larry Bates

One easy way (not tested):

#
# target value you are searching for
# nlist holds list of values to search
#
nlist=[1,3,5,7,9]
target=2
larger_value=None
for value in nlist:
if value > target:
larger_value=value
break

print larger_value
 
S

Scott David Daniels

Neal said:
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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top