[Python-ideas] Function to return first(or last) true value from list

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Feb 20 16:54:11 CET 2014


On 20 February 2014 13:11, אלעזר <elazarg at gmail.com> wrote:
> 2014-02-19 1:01 GMT+02:00 Steven D'Aprano <steve at pearwood.info>:
>> On Tue, Feb 18, 2014 at 04:25:28PM -0600, Ryan Gonzalez wrote:
>>
>> > In Python 2, you'd do this:
>> >
>> > next((x for x in mylist if x))
>>
>> That works fine in Python 3 too.
>>
>
> The problem with this approach, which I personally ran into a couple of days
> ago, is that raising StopIteration in the case of empty `mylist` is *not*
> what you want, in general.

I ran into this problem once some time ago and it took a long time to
track down the bug. Since then a bare next with no default and no
try/except StopIteration sticks out like a sore thumb every time I see
it.

Bare next() calls should be discouraged. In the situations where they
are justified I think that it deserves a code comment at the least:

    x = next(iterator)  # Propagate StopIteration


Oscar


More information about the Python-ideas mailing list