max(), sum(), next()

Luis Zarrabeitia kyrie at uh.cu
Thu Sep 4 05:40:44 CEST 2008


Quoting Laszlo Nagy <gandalf at shopzeus.com>:

> bearophileHUGS at lycos.com wrote:
> > Empty Python lists [] don't know the type of the items it will
> > contain, so this sounds strange:
> >
> >   
> >>>> sum([])
> >>>>         
> > 0
> >
> > Because that [] may be an empty sequence of someobject:
> >   
> 
> You are right in that sum could be used to sum arbitrary objects. 
> However, in 99.99% of the cases, you will be summing numerical values. 
> When adding real numbers, the neutral element is zero. ( X + 0 = X) It 
> is very logical to return zero for empty sequences.

Even better:

help(sum) shows

===
sum(...)
    sum(sequence, start=0) -> value
    
    Returns the sum of a sequence of numbers (NOT strings) plus the value
    of parameter 'start'.  When the sequence is empty, returns start.
===

so the fact that sum([]) returns zero is just because the start value is zero...
sum([],object()) would return an object().

BTW, the original code:

>>> sum(s for s in ["a", "b"] if len(s) > 2)

wouldn't work anyway... it seems that sum doesn't like to sum strings:

>>> sum(['a','b'],'')

<type 'exceptions.TypeError'>: sum() can't sum strings [use ''.join(seq) instead]

Cheers,

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie





More information about the Python-list mailing list