A small report summarizes a collection without creating additional indexing logic.
What You Need to Understand
sum() adds numeric values in an iterable to an optional starting value. It works on an iterable and is often clearer than writing a manual accumulation or search loop.
When to Use It
A small report summarizes a collection without creating additional indexing logic.
Step-by-Step Python Example
expenses = [7.5, 12.0, 3.0]
print(sum(expenses))
print(sum([1, 2, 3], start=10))
How the Example Works
The first sum is 22.5; the second begins at 10 and produces 16.
Example Output
22.5
16
6
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
values = (value for value in [1, 2, 3])
print(sum(values))
Important Behavior and Edge Cases
Use "".join(...) for strings and Decimal or integer cents for money; sum() is not a string concatenation tool.
Try It Yourself
Adapt the values and predict the result, then verify it in Python.
Common Beginner Mistakes
- Use
"".join(...)for strings andDecimalor integer cents for money;sum()is not a string concatenation tool. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
sum()adds numeric values in an iterable to an optional starting value.- The first sum is 22.5; the second begins at 10 and produces 16.
- Use
"".join(...)for strings andDecimalor integer cents for money;sum()is not a string concatenation tool.