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

Eric Snow ericsnowcurrently at gmail.com
Fri Feb 21 23:16:16 CET 2014


On Fri, Feb 21, 2014 at 2:56 AM, Peter Otten <__peter__ at web.de> wrote:
> אלעזר wrote:
>
>> What is the "classic" use case for next() raising StopIteration, to be
>> silently caught ? We need __next__ to do so in for loops, but when do we
>> need it in the functional form?
>
> Pretty much every generator that treats the first item(s) specially, like
> the one I gave above:
>
>>> def process_source(source):
>>>     it = iter(source)
>>>     first = next(it)
>>>     for item in it:
>>>         yield first * item
>
> Or these:
>
> http://docs.python.org/dev/library/itertools.html#itertools.accumulate
> http://docs.python.org/dev/library/itertools.html#itertools.groupby
> http://docs.python.org/dev/library/itertools.html#itertools.islice
> ...
>
> The behaviour of next() is really a feature rather than a bug.

It's also nice that you can pass it a default to avoid StopIteration
in one-off iteration cases (like you cited above):

  first = next(it, 0)

or generically:

  next((x for x in []), None)

-eric


More information about the Python-ideas mailing list