[Tutor] How sum() works in python

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 1 04:33:38 EDT 2017


On 01/08/17 07:06, ramakrishna reddy wrote:

>> sum([1,2,3]) returns 6.
> 
> But sum with [] 'empty list' as second parameter returns as below.
> 
>> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]

An interesting question, I wasn't aware that you could
add lists with sum.

However, the results seem clear enough. Let's start with the help()
description:
#################
Help on built-in function sum in module builtins:

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

    Return the sum of an iterable of numbers (NOT strings) plus
    the value of parameter 'start' (which defaults to 0).
    When the iterable is empty, return start.
#################

And lets see how it behaves with integers first:
>>> sum([1,2,3])   # use start default of 0
6
>>> sum([1,2,3],0) # use explicit start=0
6
>>> sum([1,2,3],1) # use start=1
7
>>> sum([1,2,3],9) # start = 9
15

So in each case we get the sum of the items in the iterable
plus the value of start. sum() is effectively doing

result = start
for n in iterable: result += n
return result

Now lets try using a list of lists:

>>> sum([ [1,2,3],[3,4,5] ])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

We get a type error because the start uses 0 and we can't
add an int and a list. So let's provide a list as the
start value:

>>> sum([ [1,2,3],[3,4,5] ], [])
[1, 2, 3, 3, 4, 5]
>>>

We now get the behaviour you saw because it adds the
three lists together using the same algorithm as above.

And if we use a non-empty start it becomes even more clear:

>>> sum([ [1,2,3],[3,4,5] ], [42])
[42, 1, 2, 3, 3, 4, 5]

We could use tuples instead of lists and get the same result.

What is interesting is that if we try the same thing with
other iterables, such as a string, it doesn't work, even
though string addition is defined. There is obviously
some type checking taking place in there.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list