max(), sum(), next()

Terry Reedy tjreedy at udel.edu
Thu Sep 11 00:44:07 EDT 2008



Mensanator wrote:
> On Sep 10, 5:36 pm, Terry Reedy <tjre... at udel.edu> wrote:

>> Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be
>> the most common use of reduce.  Sum(s,start) replaces the much less
>> common reduce(lambda x,y: x+y, s, start).
>>
>> Reduce(S, s), where S = sum function, raises an exception on empty s.
>> So use that and you are no worse off than before.

> What am I doing wrong?
 >>>> S = sum
[snip]

Taking me too literally out of context.  I meant the sum_of_2 function 
already given in the example above, as you eventually tried.

def S(x,y): return x+y

Sorry for the confusion.

...
>>>> reduce(lambda x,y:x+y,s)
> 6
> 
>>>> s=[]
>>>> reduce(lambda x,y:x+y,s)
> Traceback (most recent call last):
>   File "<pyshell#17>", line 1, in <module>
>     reduce(lambda x,y:x+y,s)
> TypeError: reduce() of empty sequence with no initial value

These two are exactly what I meant.

> This is supposed to happen. But doesn't reduce(S,s) work
> when s isn't empty?

It did.  You got 6 above.  The built-in 'sum' takes an iterable, not a 
pair of numbers.

tjr




More information about the Python-list mailing list