Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > sum works in sequences (Python 3)

Reply
Thread Tools

sum works in sequences (Python 3)

 
 
Hans Mulder
Guest
Posts: n/a
 
      09-19-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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
sum for sequences? kj Python 54 04-06-2010 02:51 PM
When I turn on my PC, it works, works, works. Problem! Fogar Computer Information 1 01-17-2006 12:57 AM
Problems with asp loading sequences arun.hallan@gmail.com ASP .Net 2 12-16-2005 10:22 AM
vhdl textio and escape sequences Olaf Petzold VHDL 1 11-28-2005 06:22 PM
After rebooting my PC works, works, works! Antivirus problem? Adriano Computer Information 1 12-15-2003 05:30 AM



Advertisments