The sum(iterable, start=0) built-in function sums numbers from left to right across an iterable, adding an optional initial accumulator.
Arithmetic Accumulation & Generator Reductions: sum() operates in linear O(N) time across lists, tuples, sets, and generator streams. It accepts an optional start value (which can be a number, list, or tuple, but never a string). For high-precision scientific floats, see math.fsum(). To find extrema or calculate powers, see min(), max(), and pow().
The sum() function accepts an iterable and an optional initial starting value:
# Formal syntax of built-in sum()
total = sum(iterable, start=0)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
iterable |
Iterable[T] |
An iterable yielding numeric elements (int, float, complex) or combinable objects. |
start |
Numeric, list, tuple | Initial value added to the accumulated sum. Defaults to 0. Strings are explicitly rejected. |
| Return Value | Same as accumulator | Returns the accumulated sum. Empty iterables return the start value. |
The return type reflects the operands being added. If all items are integers, an integer is returned; if any float is present, a float is returned:
# 1. Summing integers in a list
numbers = [10, 20, 30, 40]
print("List sum: ", sum(numbers)) # 100
print("Type: ", type(sum(numbers))) #
# 2. Summing floats in a tuple
coords = (2.5, 4.0, 1.5)
print("Tuple sum:", sum(coords)) # 8.0
print("Type: ", type(sum(coords))) #
# 3. Summing unique values in a set
unique_vals = {5, 10, 15, 10} # duplicate 10 is discarded
print("Set sum: ", sum(unique_vals)) # 30
Output:
List sum: 100
Type:
Tuple sum: 8.0
Type:
Set sum: 30
The start parameter provides an initial offset added to the total. It can also be set to [] or () to concatenate sequences:
# 1. Using an initial numeric offset
base_fee = 50
cart_prices = [15, 25, 10]
print("Total with base fee:", sum(cart_prices, start=base_fee))
# 2. Flattening a list of lists using start=[]
nested = [[1, 2], [3, 4], [5]]
flattened = sum(nested, start=[])
print("Flattened list: ", flattened)
# 3. Combining tuples with start=()
tuple_nested = ((1, 2), (3, 4))
combined = sum(tuple_nested, start=())
print("Combined tuple: ", combined)
Output:
Total with base fee: 100
Flattened list: [1, 2, 3, 4, 5]
Combined tuple: (1, 2, 3, 4)
Due to IEEE 754 binary floating-point representation limits, repeated addition of floats with built-in sum() can accumulate rounding errors. Use math.fsum() for exact precision:
import math
# Demonstrating precision loss with standard sum() on small floats
small_floats = [0.1] * 10
standard_total = sum(small_floats)
fsum_total = math.fsum(small_floats)
print("sum([0.1]*10): ", standard_total) # 0.9999999999999999
print("math.fsum([0.1]*10): ", fsum_total) # 1.0
Output:
sum([0.1]*10): 0.9999999999999999
math.fsum([0.1]*10): 1.0
sum() pairs with generator expressions to count items or aggregate dictionary values without pre-allocating intermediate lists:
# 1. Summing dictionary values
cart = {"apple": 2.50, "bread": 3.00, "milk": 1.80}
print("Cart total:", sum(cart.values()))
# 2. Generator expression (memory efficient, no intermediate list)
even_squares = sum(x**2 for x in range(1, 21) if x % 2 == 0)
print("Sum of even squares (1-20):", even_squares)
# 3. Counting items matching a condition (True evaluates to 1)
scores = [78, 92, 85, 64, 99, 88]
honor_roll_count = sum(1 for s in scores if s >= 90)
print("Honor roll students:", honor_roll_count)
Output:
Cart total: 7.3
Sum of even squares (1-20): 1540
Honor roll students: 3
Below are real-world recipes utilizing sum() for invoice calculations and weighted averages:
# Recipe A: Invoice subtotal and tax calculation
prices = [19.99, 45.50, 12.00, 8.75]
subtotal = sum(prices)
tax = subtotal * 0.05
grand_total = round(subtotal + tax, 2)
print(f"Subtotal: {subtotal:.2f}")
print(f"Tax (5%): {tax:.2f}")
print(f"Grand Total: {grand_total:.2f}")
# Recipe B: Weighted average computation
grades = [85, 90, 78]
weights = [0.2, 0.5, 0.3]
weighted_avg = sum(g * w for g, w in zip(grades, weights))
print(f"Weighted average score: {weighted_avg:.2f}")
Output:
Subtotal: 86.24
Tax (5%): 4.31
Grand Total: 90.55
Weighted average score: 85.40
sum(["a", "b"]) explicitly raises TypeError: sum() can't sum strings [use ''.join(seq) instead] to prevent quadratic copy overhead.sum(nested, []) takes quadratic O(N^2) time because each concatenation reallocates the accumulated list. Use itertools.chain.from_iterable() for large lists.sum([]) returns 0 (or the specified start value).# Pitfall 1: Strings cannot be concatenated with sum()
words = ["Hello", "World"]
try:
sum(words)
except TypeError as err:
print("TypeError caught:", err)
# Correct approach: str.join()
print("Correct join: ", " ".join(words))
# Pitfall 2: O(N^2) quadratic time with sum() on large list of lists
# Use itertools.chain.from_iterable() for massive collections instead of sum(..., [])
Output:
TypeError caught: sum() can't sum strings [use ''.join(seq) instead]
Correct join: Hello World
Practice numeric accumulations, generator counting, and precision benchmarks in our companion Jupyter Notebook:
Explore interactive code cells, benchmark sum vs math.fsum precision, implement weighted averages, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify sum() mechanics:
def test_sum_mechanics():
# 1. Basic sums
assert sum([10, 20, 30]) == 60
assert sum([10, 20], start=5) == 35
assert sum([]) == 0
# 2. Generator condition counting
assert sum(1 for x in [5, 12, 18, 3] if x > 10) == 2
# 3. List flattening
assert sum([[1], [2, 3]], []) == [1, 2, 3]
print("All sum() unit assertions passed! 100% verified.")
test_sum_mechanics()
Output:
All sum() unit assertions passed! 100% verified.
Computes high-precision floating-point summations without rounding drift.
Calculates quotient and remainder in a single machine operation.
Finds the smallest item in an iterable or set of arguments.
Finds the largest item in an iterable or set of arguments.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.