Python sum() Function

Sums items of an iterable

Basic Example

Example: Return the sum of all items in a list

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

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)

Parameters

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

More Examples

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