reduce in loop

Terry Reedy tjreedy at udel.edu
Mon Apr 5 02:02:47 CEST 2010


On 4/4/2010 7:46 PM, monkeys paw wrote:
> Why does the following fail with the Traceback?
>
> def add(x,y): return x+y
> for rrr in range(1,20):

I presume that this was 'for r...'

> reduce(add, range(1, r))

and that this was indented.

> Traceback (most recent call last):
> File "<interactive input>", line 2, in <module>
> TypeError: reduce() of empty sequence with no initial value

Just what it says. To debug this sort of this, try printing values just 
before the line that fails. When r is 1, range(1,1) = []. So either 
start r at 2 or add the third arg to reduce(add, range(1,r), 0).

Terry Jan Reedy






More information about the Python-list mailing list