Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 870
Kaizer von Maanen Avatar asked Jul 15 '13 23:07

Kaizer von Maanen


People also ask

What does sum () do in Python?

Python sum() Function The sum() function returns a number, the sum of all items in an iterable.

How many arguments does sum take in Python?

You can call sum() with the following two arguments: iterable is a required argument that can hold any Python iterable. The iterable typically contains numeric values but can also contain lists or tuples. start is an optional argument that can hold an initial value.


2 Answers

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).

like image 175
Lasse V. Karlsen Avatar answered Oct 06 '22 00:10

Lasse V. Karlsen


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.

like image 27
AnnaRaven Avatar answered Oct 05 '22 23:10

AnnaRaven