Find first in sequence (simple question)

Gerrit gerrit at nl.linux.org
Mon Sep 13 21:41:07 CEST 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.

You could do:

# WARNING: Untested code
index = -1
for i in x:
    if i > n:
        index = i
        break

This would work, and unless you can make assumption about the list, I
doubt it can be faster. If you can assume that for example the list is
sorted, it should be possible to do it faster, although I would not know
exactly how.

yours,
Gerrit.

-- 
Weather in Twenthe, Netherlands 13/09 20:55:
	14.0°C   wind 5.4 m/s SSW (57 m above NAP)
-- 
Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL.
Experiences with Asperger's Syndrome:
	EN http://topjaklont.student.utwente.nl/english/
	NL http://topjaklont.student.utwente.nl/



More information about the Python-list mailing list