sum(strings)

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Jun 19 11:52:25 EDT 2003


Steve McAllister <nosp at m.needed> wrote in news:bcsjii$3vf$1 at alto.univ-
mlv.fr:

> Why does sum reject strings?  Is it a matter of efficiency of the 
> underlying implementation?
> 
It has a specific check to reject strings. If you play games with the 
starting value, then it will quite happily add up strings:

>>> class C:
       def __add__(self, other):
          return other

>>> sum(["abc", "def", "ghi"], C())
'abcdefghi'

I can see that for adding strings you would be better to use str.join, but 
the explicit type check seems to be very un-pythonic.

Also to add up anything non-numeric, you have to provide a starting value. 
The implementation is approximately equivalent to:

def sum(seq, start=sentinal):
    iterable = iter(seq)
    if start is sentinal:
        result = 0
    else:
        result = start

    if isinstance(result, basestring):
        raise TypeError("sum() can't sum strings")

    for item in iterable:
        result += item
    return result

I would have thought a simpler implementation would be:

def sum(seq, start=sentinal):
    iterable = iter(seq)
    if start is sentinal:
        result = iterable.next()
    else:
        result = start

    for item in iterable:
        result += item
    return result

which has the advantage that you can sum anything addable without 
specifying a start value.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list