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
Python sum() Function The sum() function returns a number, the sum of all items in an iterable.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With