sum() iterates once over its argument, adding each element to a running total that begins at start, which is 0 by default. It works with any numeric iterable — lists, tuples, generators, ranges — and the start parameter lets you provide a non-zero base for the total, though the += operator or itertools.chain is the more efficient choice for concatenating sequences rather than summing them.
1Understanding sum()
sum() iterates once over its argument, adding each element to a running total that begins at start, which is 0 by default. It works with any numeric iterable — lists, tuples, generators, ranges — and the start parameter lets you provide a non-zero base for the total, though the += operator or itertools.chain is the more efficient choice for concatenating sequences rather than summing them.
sum() only adds numbers efficiently — don't use it to flatten a list of lists, since repeatedly concatenating with + is quadratic time; use itertools.chain.from_iterable() instead.
prices = [19.99, 5.50, 3.25]
total = sum(prices)
print(total)2Practical Example
Here is a real-world application of sum() showing how it is used in production Python code.
orders = [{"item": "Book", "qty": 2}, {"item": "Pen", "qty": 5}]
total_items = sum(order["qty"] for order in orders)
print(total_items)3Best Practices
Follow these guidelines when working with sum():
1. Pass a generator expression directly to sum(), instead of building an intermediate list first
2. Use sum() with a generator expression and an if condition to count items matching a condition
3. Avoid sum() for concatenating lists/strings — use ''.join() for strings and itertools.chain for lists
Tip: sum() only adds numbers efficiently — don't use it to flatten a list of lists, since repeatedly concatenating with + is quadratic time; use itertools.chain.from_iterable() instead.
prices = [19.99, 5.50, 3.25]
total = sum(prices)
print(total)