Aggregate numeric values
Compute a total from values held in a list, tuple, or other iterable.
Python · Function
sum() adds the items of an iterable from left to right, starting with an optional initial value. It returns the resulting total and is intended primarily for numeric items.
sum() consumes an iterable and combines its items from left to right, beginning with start, which defaults to 0. It returns the resulting total; the items are normally numeric and start must not be a string.
sum(iterable, /, *, start=0)| Name | Type | Description |
|---|---|---|
iterable | iterable | An iterable whose items are added. |
start | object | Initial value added before the iterable's items; defaults to 0 and cannot be a string. |
The total of start and the iterable's items.
numbers = [1, 2, 3]
total = sum(numbers, start=10)
print(total) # 16Adds the iterable's values from left to right, beginning with the supplied starting value.
Compute a total from values held in a list, tuple, or other iterable.
Begin an accumulation with an existing offset or subtotal.
Consume generated values without first materializing them into a collection.
sum() accepts an iterable and an optional keyword-only start value that defaults to 0. It adds the start value and iterable items from left to right, then returns the total.
Follow-up: What does sum([], start=10) return? It returns 10 because the empty iterable contributes no items and the initial value remains.
The iterable's items are normally numbers, so numeric values can be accumulated directly. The function processes them in iteration order rather than requiring a sequence.
Follow-up: Can a generator be passed? Yes: because the parameter is an iterable, a generator can supply the items as it is consumed.
start is optional and defaults to 0, and it must not be a string. Supplying another suitable initial value lets the total begin from a nonzero value.
Follow-up: Why is an explicit start useful? It lets the caller include an initial offset without separately adding it after the iterable is summed.
math.fsum()iter()