On Mon, Jan 12, 2009 at 12:21 PM, bob gailer <bgai...@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.

Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to