[Tutor] Selecting first matching element from a list

Kent Johnson kent37 at tds.net
Mon Jan 12 19:09:08 CET 2009

On Mon, Jan 12, 2009 at 12:21 PM, bob gailer <bgailer at gmail.com> wrote:
> Noufal Ibrahim wrote:
>> Hello everyone,
>>       What is the pythonic way 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.
> 1) itertools.dropwhile(cond, lst) will return a list with the desired
> element first.

I think you mean itertools.takewhile(). Note that it returns an
iterable, not a list; use next() to get the first element.

You can also use a generator expression to do pretty much the same thing:
(x for x in lst if cond(x)).next()

This will raise StopIteration if no element meets the condition.
Compared to the list comp, it has the advantage of stopping when it
finds the first matching element; the list comp finds all matches.


More information about the Tutor mailing list