Python Reference ยท Built-in Functions
Python sum() function
Reference for Python sum(): add up numbers in any iterable, the start value, floating-point accuracy, math.fsum, and why sum() is slow for strings and lists.
The built-in sum() function adds the items of an iterable from left to right and returns the total. It starts from 0 (or a start value you provide) and works with integers, floats, Fraction, Decimal and anything else that supports + with the start value.
An empty iterable gives the start value, so sum([]) is 0. Combined with a generator expression, sum() becomes a compact way to count or total things that match a condition.
sum([1, 2, 3]) # 6 sum(len(w) for w in ["a", "bb"]) # 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
sum(iterable, /, start=0)
| Name | Description |
|---|---|
iterable |
The items to add. |
start |
The value added first and returned for an empty iterable. Can be passed by keyword since Python 3.8. |
Return value: the total, of whatever type the additions produce.
Raises: TypeError when an addition is not supported, including when the items are strings.
Usage notes
- Strings are not summed.
sum(["a", "b"])fails because it starts from the integer0, andsum(["a", "b"], "")is refused on purpose, because repeated concatenation is quadratic. Use"".join(items). - Lists and tuples work if you pass a matching start (
sum(lists, [])), but this copies repeatedly and is slow for many items. Preferitertools.chain.from_iterable()or a comprehension. - Floating-point error. Before Python 3.12, adding
0.1ten times withsum()gave0.9999999999999999. Since 3.12sum()of floats uses compensated summation and is much more accurate, butmath.fsum()is the tool that guarantees a correctly rounded result. UseDecimalfor money. - Booleans count as 0 and 1, so
sum(condition for ...)counts matches. - Order matters only for non-numeric
+; for numbers the result is the same either way, apart from float rounding. - Dictionaries iterate over keys, so sum the
.values(). - Averages.
sum(x) / len(x)needs a sized collection; for iterators usestatistics.mean(). - Large data. For arrays of numbers, NumPy's
np.sumis much faster.
Related
min(),max(),len(),divmod(),all(),sorted()- Lessons: Numbers, Comprehensions, Math and random