sum works in sequences (Python 3)
Hans Mulder
hansmu at xs4all.nl
Wed Sep 19 18:25:40 EDT 2012
On 19/09/12 17:07:04, Alister wrote:
> 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
Actually, the 'sum' builtin function is quite capable of
concatenatig objects, for example lists:
>>> sum(([2,3], [5,8], [13,21]), [])
[2, 3, 5, 8, 13, 21]
But if you pass a string as a starting value, you get an error:
>>> sum([], '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
In fact, you can bamboozle 'sum' into concatenating string by
by tricking it with a non-string starting value:
>>> class not_a_string(object):
... def __add__(self, other):
... return other
...
>>> sum("rtarze", not_a_string())
'rtarze'
>>> sum(["Monty ", "Python", "'s Fly", "ing Ci", "rcus"],
... not_a_string())
"Monty Python's Flying Circus"
>>>
Hope this helps,
-- HansM
More information about the Python-list
mailing list