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
| Parameter | Description |
|---|---|
iterable |
Numbers to add. |
start optional |
Added to the total; also the result for an empty iterable. Default: 0 |
Return value
The total.
Examples
print(sum([1, 2, 3, 4]))
print(sum(range(101)))
print(sum([0.1] * 10))
Output
10 5050 1.0
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
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), notsum():sum(["a", "b"], "")raisesTypeError. - For exact decimal totals (money), sum
Decimalvalues, or usemath.fsum()for floats.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.8 | start can be passed as a keyword argument. |
| Python 3.12 | Sums of floats use a more accurate algorithm (Neumaier summation). |
Related
len()· Return the number of items in a container: characters in a string, items in a list, keys in a dict, and so on.max()· Return the largest item in an iterable, or the largest of several arguments. Supports a key function and a default.min()· Return the smallest item in an iterable, or the smallest of several arguments. Supports a key function and a default.map()· Apply a function to every item of one or more iterables and return a lazy iterator of the results.- Python Lists · tutorial
- Python Math · tutorial