By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 924 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

Find first in sequence (simple question)

P: n/a
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.
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

"Neal D. Becker" <nd*******@verizon.net> wrote in message
news:ma**************************************@pyth on.org...
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.

Jul 18 '05 #2

P: n/a
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
Sc***********@Acm.Org
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.