In Python, sum(iterable) adds up the items of an iterable (a list, tuple, set, range, generator, ...) and returns the total. An empty iterable gives 0.
The optional start value is added to the total and is also what an empty iterable returns. Since Python 3.8 you can pass it by keyword: sum(values, start=10). sum() refuses strings; use "".join() for text.
sum() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Pass any iterable of numbers, and optionally a start value.
python
total = sum(numbers)
total_plus = sum(numbers, start)
Call
What it does
sum([1, 2, 3])
Returns 6.
sum([1, 2, 3], 10)
Returns 16: the start value is added.
sum(x * x for x in range(4))
Returns 14 from a generator expression.
sum([])
Returns 0, the default start.
A generator expression needs no extra brackets when it is the only argument: sum(x for x in data).
Library declarations
python
sum(iterable, /, start=0)
Parameters
Parameter
Description
iterable
Required. An iterable of numbers (or other objects that support +, except strings).
start
Optional. The value the total starts from. Default 0. Keyword form allowed since Python 3.8.
Return Value
Return Value
Description
number
start plus every item. The type follows the items: ints give an int, any float gives a float.
Python Examples
Example 1 — Totals, Averages, and the start Value
Add a list of scores, compute an average with len(), and see what start and an empty list do.
[1, 2, 3, 4, 5]
Use ''.join() for strings: sum is for numbers
1.0
How It Works
Lists support +. Starting from an empty list, sum() concatenates [1, 2] + [3] + [4, 5].
Fine for small data. Each + copies the list so far; for many lists, itertools.chain is faster.
Strings are blocked. Even with "" as start, sum() raises TypeError and points you to join().
Accurate floats.math.fsum() tracks the lost low-order bits, so ten 0.1 values total exactly 1.0.
Frequently Asked Questions
Call sum(my_list). It works with any iterable of numbers, including tuples, sets, ranges, and generator expressions.
It is added to the total and returned for an empty iterable. sum([1, 2], 10) returns 13.
sum() deliberately rejects strings because repeated + on strings is slow. Use "".join(words) or " ".join(words) instead.
Floats are binary approximations, so small errors add up. Python 3.12 made sum() of floats more accurate, and math.fsum() gives the most accurate result on all versions.
Use sum(my_dict.values()). sum(my_dict) would add the keys instead.