C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: An iterable like a list we want to sum. The list must have summable elements like integers, not sub lists.
Argument 2: A value that is added to the sum of the iterable's elements. We can use this argument to sum previous sums.
Python program that uses sum, two arguments
values = [10, 20, 5]
# The sum of the 3 values is this number.
result = sum(values)
print(result)
# Use sum with two arguments.
# ... The second argument is added to the element sum.
result = sum(values, 1000)
print(result)
Output
35
1035
Python program that uses sum, nested list error
# This list has a nested list element.
# ... It cannot be summed with sum.
values = [10, [20, 30]]
# This will cause a TypeError.
result = sum(values)
print(result)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 9, in <module>
result = sum(values)
TypeError: unsupported operand type(s) for +: 'int' and 'list'