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

Peter Otten __peter__ at web.de
Fri Feb 21 10:56:30 CET 2014


אלעזר 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.



More information about the Python-ideas mailing list