Skip to content
Tutorials Center
My learning

Topics

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.

Python
sum([1, 2, 3])                      # 6
sum(len(w) for w in ["a", "bb"])    # 3

Try it

Python Totals and counting

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.

Python Precision, start and strings

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

Python
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 integer 0, and sum(["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. Prefer itertools.chain.from_iterable() or a comprehension.
  • Floating-point error. Before Python 3.12, adding 0.1 ten times with sum() gave 0.9999999999999999. Since 3.12 sum() of floats uses compensated summation and is much more accurate, but math.fsum() is the tool that guarantees a correctly rounded result. Use Decimal for 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 use statistics.mean().
  • Large data. For arrays of numbers, NumPy's np.sum is much faster.