469,354 Members | 2,035 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,354 developers. It's quick & easy.

Find first in sequence (simple question)

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
2 1605
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
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.

Similar topics

108 posts views Thread by Bryan Olson | last post: by
18 posts views Thread by Andy Green | last post: by
9 posts views Thread by Tony Girgenti | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.