[Tutor] Selecting first matching element from a list

wesley chun wescpy at gmail.com
Mon Jan 12 19:00:20 CET 2009


> 1) itertools.dropwhile(cond, lst) will return a list with the desired element first.

i think in order to use this, the OP needs to invert his Boolean logic
because it *drops* elements while the conditional is True. as soon as
it hits False the 1st time, all remaining elements (including the one
that breaks the "while) is yielded. once he flips it, a single call to
next() with a try-except StopIteration will be similar to the code in
your msg:

results = itertools.dropwhile(invCond, lst)
try:
     desired = results.next()
except StopIteration:
    deal with element not found

bob's 2) and 3) are spot on.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list