Kaizer von Maanen
Kaizer von Maanen

Reputation: 987

Python: I do not understand the complete usage of sum()

Of course I get it you use sum() with several numbers, then it sums it all up, but I was viewing the documentation on it and I found this:

sum(iterable[, start])

What is that second argument "[, start]" for? This is so embarrasing, but I cannot seem to find any examples with google and the documentation is fairly cryptic for someone who tries to learn the language.

Is it a list of some sort? I cannot get it to work. Here is an example of one of my attempts:

>>> sum(13,4,5,6,[2,4,6])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum expected at most 2 arguments, got 5

Upvotes: 8

Views: 7696

Answers (2)

AnnaRaven
AnnaRaven

Reputation: 63

Also, please keep in mind that if you create a nested list (like you sortof have above) sum will give you an error (trying to add an integer to a list, isn't clear - are you trying to append or add it to the sum of the list or what?). So will trying to use two lists, + is overloaded and would just normally concatenate the two lists into one but sum tries to add things so it wouldn't be clear what you're asking.

It's easier to explain with examples:

>>> mylist = [13, 4, 5, 6, [2,4,6]]
>>> sum(mylist)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> a = [13, 4, 5, 6]
>>> b = [2,4,6]
>>> c = [a,b]
>>> c
[[13, 4, 5, 6], [2, 4, 6]]
>>> sum(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> c = a+b
>>> c
[13, 4, 5, 6, 2, 4, 6]
>>> sum(c)
40
>>> sum(c, 23)
63

Hope this helps.

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391456

The start indicates the starting value for the sum, you can equate this:

sum(iterable, start)

with this:

start + sum(iterable)

The reason for your error is that you're not encapsulating the numbers to sum in an iterable, do this instead:

sum([13, 4, 5, 6])

This will produce the value of 28 (13+4+5+6). If you do this:

sum([13, 4, 5, 6], 25)

You get 53 instead (13+4+5+6 + 25).

Upvotes: 11

Related Questions