Python 3 reference · Built-in Functions

Python sum() Function

Add up the numbers in an iterable, plus an optional start value. Floats are summed with extra precision since Python 3.12.

Python 3 Since 3.0

Syntax

sum(iterable, /, start=0)

Parameters

ParameterDescription
iterable Numbers to add.
start optional Added to the total; also the result for an empty iterable. Default: 0

Return value

The total.

Examples

Add numbersTry it yourself
print(sum([1, 2, 3, 4]))
print(sum(range(101)))
print(sum([0.1] * 10))

Output

10
5050
1.0
Totals with a generatorTry it yourself
cart = [{"item": "tea", "price": 2.5, "qty": 2}, {"item": "cake", "price": 4.0, "qty": 1}]
print(sum(p["price"] * p["qty"] for p in cart))
print(sum([], start=10))

Output

9.0
10
Count matching itemsTry it yourself
words = ["red", "green", "blue"]
print(sum(len(w) for w in words))
print(sum(w.startswith("g") for w in words))  # count matches (True is 1)

Output

12
1

Common mistakes

  • To join strings use "".join(parts), not sum(): sum(["a", "b"], "") raises TypeError.
  • For exact decimal totals (money), sum Decimal values, or use math.fsum() for floats.

Version history

VersionChange
Python 3.0Added
Python 3.8start can be passed as a keyword argument.
Python 3.12Sums of floats use a more accurate algorithm (Neumaier summation).