Python sum() Function

Sums items of an iterable

Usage

The sum() function sums the items of an iterable and returns the total.

If you specify an optional parameter start, it will be added to the final sum.

This function is created specifically for numeric values. For other values, it will raise TypeError.

Syntax

sum(iterable,start)

Python sum() function parameters
ParameterConditionDescription
iterableRequiredAn iterable (such as list, tuple etc.)
startOptionalA value to be added to the final sum.
Default is 0.

Examples

Example: Return the sum of all items in a list

L = [1, 2, 3, 4, 5]
x = sum(L)
print(x)    # 15

If you specify an optional parameter start, it will be added to the final sum.

Example: Start with ’10’ and add all items in a list

L = [1, 2, 3, 4, 5]
x = sum(L, 10)
print(x)    # 25