sum works in sequences (Python 3)

Alister alister.ware at ntlworld.com
Wed Sep 19 11:07:04 EDT 2012


On Wed, 19 Sep 2012 16:41:20 +0200, Franck Ditter 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...
> 
>     franck

Summation is a mathematical function that works on numbers
Concatenation is the process of appending 1 string to another

although they are not related to each other they do share the same 
operator(+) which is the cause of confusion.
attempting to duck type this function would cause ambiguity for example 
what would you expect from

sum ('a','b',3,4)

'ab34' or 'ab7' ?

even 'A' + 7 would return this error for same reason.
 



-- 
It is the nature of extreme self-lovers, as they will set an house on 
fire,
and it were but to roast their eggs.
		-- Francis Bacon



More information about the Python-list mailing list