sum works in sequences (Python 3)

Ian Kelly ian.g.kelly at gmail.com
Wed Sep 19 11:03:03 EDT 2012


On Wed, Sep 19, 2012 at 8:41 AM, Franck Ditter <franck at ditter.org> wrote:
> Hello,
> I wonder why sum does not work on the string sequence in Python 3 :
>
>>>> sum((8,5,9,3))
> 25
>>>> sum([5,8,3,9,2])
> 27
>>>> sum('rtarze')
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I naively thought that sum('abc') would expand to 'a'+'b'+'c'
> And the error message is somewhat cryptic...

It notes in the doc string that it does not work on strings:

sum(...)
    sum(sequence[, start]) -> value

    Returns the sum of a sequence of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the sequence is
    empty, returns start.

I think this restriction is mainly for efficiency.  sum(['a', 'b',
'c', 'd', 'e']) would be the equivalent of 'a' + 'b' + 'c' + 'd' +
'e', which is an inefficient way to add together strings.  You should
use ''.join instead:

>>> ''.join('abc')
'abc'



More information about the Python-list mailing list