[Python-ideas] Generators are iterators

Terry Reedy tjreedy at udel.edu
Fri Dec 12 23:54:01 CET 2014


On 12/12/2014 4:10 PM, Oscar Benjamin wrote:

> The function was just supposed to generate the effect. More plausible
> examples can be made. I tripped over this myself once when doing
> something with iterators that required me to extract the first item
> before processing the rest. A simple demonstration:
>
> def sum(iterable):
>      iterator = iter(iterable)
>      total = next(iterator)
>      for item in iterator:
>          total += item
>      return total

Examples like this has been posted on python-list, probably more than 
once. The answer has been to catch StopIteration (which should only come 
from next/__next__) and either return a default value or raise 
ValueError('cannot sum an empty iterable').

> results = list(map(sum, data_sources))

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list