all Python 3Built-in functionsterm
sum
numbers/collections
Sums the items of an iterable. start is the initial value.
Syntax
sum(iterable, start=0)
sum refuses to concatenate strings: sum(['a', 'b']) raises TypeError about adding int and str (start defaults to 0), and sum(['a', 'b'], '') raises one that points you at ''.join(). Flattening lists with sum(lists, []) does work, but it builds a fresh list at every step and scales quadratically, so reach for itertools.chain on anything long.
Examples
print(sum([1,2,3,4,5])) # → 15
print(sum(range(101))) # → 5050
print(sum([[1,2],[3,4]], [])) # → [1,2,3,4]
print(sum({'a':1,'b':2}.values())) # → 3
# Python 3.12+
print(sum([0.1]*10)) # → 1.0 — до 3.12 было 0.9999999999999999
See also
Open in the full glossarydocs.python.orgReport an inaccuracy