How to Add Up Numbers in Python with sum()
To get the total of a list of numbers, you don't need a loop and a running total: Python's built-in sum() adds them up for you. It works on anything you can loop over, so it also totals a dictionary's values, and it can count the items that match a condition. This guide does all three on Python 3.15.2.
Syntax
sum(<iterable>, <start>)
| Part | What it means |
|---|---|
<iterable> | The numbers to add: a list, a dictionary's .values(), a generator expression and so on |
<start> | Optional. The number to start from. It's 0 when you leave it out |
The built-in functions documentation says sum() "Sums start and the items of an iterable from left to right and returns the total. The iterable's items are normally numbers, and the start value is not allowed to be a string."
The Example
Three totals: the prices in a list, the counts in a dictionary, and how many words in a list are longer than 4 letters.
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
prices = [3, 5, 12]
print(sum(prices))
stock = {"apples": 4, "pears": 7}
print(sum(stock.values()))
words = ["daisy", "rose", "tulip", "lily"]
print(sum(1 for word in words if len(word) > 4))

The last line counts: for each word longer than 4 letters, the generator expression gives a 1, and sum() adds up the ones.
Step 2: Run It
uv run python totals.py
20
11
2

20 is 3 + 5 + 12, and 11 is the 4 apples plus the 7 pears. 2 is the number of words longer than 4 letters: daisy and tulip. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Adding up strings: sum(["a", "b"]) | TypeError: unsupported operand type(s) for +: 'int' and 'str': sum() starts from the number 0 | Join strings with "".join(["a", "b"]) |
Passing the dictionary itself: sum(stock) | sum() loops over a dictionary's keys, which are strings here, so it fails the same way | Pass stock.values() |
The documentation suggests the same: "The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence)."
FAQ
What does the start value do?
It's added to the total: sum([3, 5, 12], 100) printed 120.
Can sum() add decimals?
Yes. It adds floats too. For many floats where every last digit matters, the documentation points to math.fsum(), which adds them "with extended precision".
Conclusion
sum() added a list of prices (20) and a dictionary's values (11), and with a generator expression that gives 1 per match, it counted the long words (2). It works on numbers only: strings need "".join().
Additional Resources
- sum() — the built-in function.
- Generator expressions — the language reference.
