sum works in sequences (Python 3)

Neil Cerutti neilc at norwich.edu
Wed Sep 19 10:57:56 EDT 2012


On 2012-09-19, 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...

You got that error message because the default value for the
second 'start' argument is 0. The function tried to add 'r' to 0.
That said:

>>> sum('rtarze', '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

-- 
Neil Cerutti



More information about the Python-list mailing list