Back to Blog
Python

Python sum Function: Syntax, Behavior, and Limits

python sum function: Learn how Python's built-in sum() works, its start parameter, performance behavior, and when to choose alternatives like math.fsum or functools.re...

pythonsum functionbuilt-in functionsiterablesfloating point
Illustration of Python sum function adding numbers from a list into a total

Python's built-in sum() function adds together the items of an iterable and returns the total. It is the standard way to total a sequence of numbers without writing a manual loop. The python sum function is implemented in C, which makes it faster than an equivalent Python for loop for most inputs.

numbers = [4, 7, 9, 12] total = sum(numbers) print(total) # 32

The function takes two arguments: the iterable and an optional start value. When start is omitted, it defaults to 0. The addition is performed left to right, so sum([a, b, c], start) evaluates as start + a + b + c.

The start Parameter

The start parameter initializes the total before any items are added. This is useful when you need to begin from a non-zero baseline, such as adding a fixed fee to a list of charges.

prices = [19.99, 4.50, 8.75] total = sum(prices, start=10.00) print(total) # 43.24

The start value participates in the same addition chain as the iterable items. If you pass a list as start, the result will be a concatenated list rather than a numeric sum, because + on lists performs concatenation.

result = sum([[1, 2], [3, 4]], start=[]) print(result) # [1, 2, 3, 4]

This works, but it is rarely the clearest way to flatten a list. A list comprehension or itertools.chain is usually more readable.

What sum() Accepts

sum() works with any iterable that yields values supporting + with the start value. In practice, this means lists, tuples, sets, generators, and dictionary keys.

# Generator expression total = sum(x * 2 for x in range(10)) print(total) # 90 # Dictionary sums keys by default d = {1: "a", 2: "b", 3: "c"} print(sum(d)) # 6

When you pass a dictionary, sum() iterates over its keys, not its values. If you need to sum the values, pass d.values() explicitly.

Common Mistakes with sum()

The most frequent error is passing strings to sum(). Because the default start is the integer 0, the first addition attempts 0 + "a", which raises TypeError.

words = ["a", "b", "c"] # sum(words) # TypeError: unsupported operand type(s) for +: 'int' and 'str'

Use ''.join(words) for string concatenation. The same restriction applies to bytes and bytearrays.

Another mistake is assuming sum() handles nested structures gracefully. Summing a list of lists without a start value fails for the same reason: 0 + [1, 2] is invalid. You must supply an empty list as start, as shown earlier.

Floating-Point Precision

For floating-point numbers, sum() accumulates values left to right using standard binary floating-point arithmetic. This can introduce small rounding errors when many values are added.

import math values = [0.1] * 10 print(sum(values)) # 0.9999999999999999 print(math.fsum(values)) # 1.0

math.fsum() uses a compensated summation algorithm that tracks and corrects rounding error. It is the better choice when accuracy matters, such as in financial calculations or scientific data processing. The performance difference is negligible for typical list sizes.

Performance and Alternatives

sum() is implemented in C, so it is faster than an equivalent Python for loop for most inputs. The loop overhead is eliminated, and the addition happens in the interpreter's fast path.

# Manual loop total = 0 for n in numbers: total += n # sum() is faster for the same operation total = sum(numbers)

For large numeric arrays, numpy.sum() can be significantly faster because it operates on contiguous memory and can use vectorized instructions. However, adding numpy as a dependency is only justified when you already use it elsewhere.

functools.reduce() is an alternative when you need custom accumulation logic beyond simple addition.

from functools import reduce # Equivalent to sum(numbers) total = reduce(lambda a, b: a + b, numbers, 0)

But reduce() is slower than sum() for plain addition and is harder to read. Use it only when the accumulation rule is not a simple +.

When to Choose Each Approach

ApproachBest forTradeoff
sum()Totaling numbers from any iterableLimited to + semantics
math.fsum()Floating-point accuracySlightly slower, import required
''.join()String concatenationOnly works with strings
numpy.sum()Large numeric arraysRequires numpy dependency
functools.reduce()Custom accumulationMore verbose, slower

The decision is driven by the data type and the accuracy requirement. For integers and small float lists, sum() is the right default. For precision-sensitive float work, math.fsum() removes the rounding concern. For large arrays, numpy.sum() wins on speed, but only if numpy is already part of your stack.

python sum function: Practical Usage and Code Examples | RYUSLOG DEV