[Tutor] Selecting first matching element from a list

Noufal Ibrahim noufal at nibrahim.net.in
Mon Jan 12 16:56:55 CET 2009


Hello everyone,
        What is the pythonic was of selecting the first element of a 
list matching some condition?
        I often end up using

        [x for x in lst if cond(x)][0]

        This looks bad and raises IndexError if nothing is found which 
is ugly too.

Thanks.
-- 
~noufal
http://nibrahim.net.in/


More information about the Tutor mailing list