sum()
Adds up all the numbers in a list, tuple or any other iterable, with an optional starting value, in one short and fast call.
sum(iterable, /, start=0)sum() adds up every number in a collection: sum([4, 8, 15]) is 27. An empty collection gives 0.
Combine it with a generator expression to add up a calculation for each item, such as price times quantity for every line of a basket. Because True counts as 1, it can also count how many items pass a test.
Floats can surprise you: sum([0.1, 0.2]) is 0.30000000000000004, because 0.1 and 0.2 cannot be stored exactly. Round the result for display, or use math.fsum() for the most accurate total. And sum() refuses strings on purpose; join text with str.join() instead.
Parameters
| Parameter | What it is |
|---|---|
iterablerequired | The numbers to add: a list, tuple, set, range, generator and so on. |
startoptional, default 0 | A value added to the total; also what you get for an empty iterable. Can be given by name: start=100. |
Return value
The total. Whole numbers give an int; if any item is a float, the total is a float.
Examples
1Add up a list
expenses = [12.50, 7.25, 30.00, 4.75]
print(sum(expenses))
print(sum(range(1, 101)))
print(sum([]))54.5 5050 0
2Add a starting value
deposits = [200, 150, 75]
opening_balance = 1000
print(sum(deposits, start=opening_balance))1425
3Total of a shopping basket
basket = [("bread", 2.40, 2), ("cheese", 5.90, 1), ("apples", 0.45, 6)]
total = sum(price * qty for name, price, qty in basket)
print(f"Total: {total:.2f}")Total: 13.40
The expression inside the brackets is worked out for each item and passed straight to sum(), without building a list first.
4Count items that pass a test
temps = [18, 24, 31, 27, 16, 33]
hot_days = sum(t > 25 for t in temps)
print(hot_days, "hot days")3 hot days
Each comparison gives True or False, which count as 1 and 0.
5Floats, a plain loop and math.fsum()
Adding floats one by one lets tiny errors pile up:
import math
tenths = [0.1] * 10
total = 0.0
for t in tenths:
total += t
print(total)
print(math.fsum(tenths))
print(round(total, 2))0.9999999999999999 1.0 1.0
math.fsum() keeps track of the lost bits and gives the correctly rounded total on every Python version. Since Python 3.12, sum() itself is also more careful with floats and gives 1.0 here, while 3.11 and older give 0.9999999999999999; use fsum() when the last digit matters.
Common mistakes
Adding up strings
sum() will not join text, even with a string as start. Use str.join().
words = ["to", "get", "her"]
try:
print(sum(words, ""))
except TypeError:
print("TypeError: sum() cannot add strings")
print("".join(words))TypeError: sum() cannot add strings together
Numbers stored as text
Values from input or a CSV file are strings. Convert each one before adding.
cells = ["3", "4", "5"]
try:
print(sum(cells))
except TypeError:
print("TypeError: cannot add int and str")
print(sum(int(c) for c in cells))TypeError: cannot add int and str 12
Questions people ask
How do I sum a list of numbers in Python?
sum(numbers). For the average, divide by the count: sum(numbers) / len(numbers).
How do I sum the values of a dictionary?
sum(d.values()).
How do I sum a column in a list of rows?
Pick the column in a generator: sum(row[2] for row in rows).
How do I flatten a list of lists?
[x for inner in lists for x in inner]. sum(lists, []) also works but gets very slow on big data.