sum()
The built-in sum()
function provides a Pythonic way to add together the items of an iterable. It efficiently computes the total sum of numeric values, with the option to include an initial value for the summation process:
>>> sum([1, 2, 3, 4, 5])
15
>>> sum([1, 2, 3, 4, 5], start=100)
115
sum()
Signature
sum(iterable, /, start=0)
Arguments
Argument | Description | Default Value |
---|---|---|
iterable |
Any Python iterable containing numeric values. It can also hold concatenable objects, such as lists and tuples. | Required argument |
start |
An optional argument to initialize the summation. It can be a number, list, or tuple, but not a string. | 0 |
Return Value
- The sum of the
start
value and the values in the input iterable from left to right. - The return value’s data type matches the type of the elements in the input iterable.
sum()
Examples
With a list of integers as an argument:
>>> sum([1, 2, 3, 4, 5])
15
With a tuple of floating-point numbers as an argument:
>>> sum((10.5, 20.3, 30.2))
61.0
With a comprehension that generates square values:
>>> sum([x ** 2 for x in range(1, 6)])
55
With a starting value:
>>> sum([1, 2, 3], start=10)
16
With a list of Decimal
values:
>>> from decimal import Decimal
>>> sum([Decimal("10.2"), Decimal("12.5"), Decimal("11.8")])
Decimal('34.5')
With a list of rational numbers:
>>> from fractions import Fraction
>>> sum([Fraction(51, 5), Fraction(25, 2), Fraction(59, 5)])
Fraction(69, 2)
sum()
Common Use Cases
The most common use cases for the sum()
function include the following:
- Calculating the total of a series of numeric values.
- Summing numeric values as part of a larger mathematical computation.
sum()
Real-World Example
Say you’re tracking daily sales figures across different stores and want to calculate the total sales for the week. Here’s how you can do it using sum()
:
>>> weekly_sales = [
... [100, 150, 200], # Monday
... [80, 120, 160], # Tuesday
... [130, 170, 210], # Wednesday
... [90, 110, 140], # Thursday
... [200, 250, 300] # Friday
... ]
>>> sum(sum(daily_sales) for daily_sales in weekly_sales)
2510
In this example, sum()
helps efficiently compute the total sales by first summing each day’s sales figures and then aggregating those daily totals.
Related Resources
Tutorial
Python's sum(): The Pythonic Way to Sum Values
In this step-by-step tutorial, you'll learn how to use Python's sum() function to add numeric values together. You also learn how to concatenate sequences, such as lists and tuples, using sum().
For additional information on related topics, take a look at the following resources:
- Lists vs Tuples in Python (Tutorial)
- Numbers in Python (Tutorial)
- Representing Rational Numbers With Python Fractions (Tutorial)
- Python range(): Represent Numerical Ranges (Tutorial)
- Summing Values the Pythonic Way With sum() (Course)
- Lists and Tuples in Python (Course)
- Lists vs Tuples in Python (Quiz)
- The Python range() Function (Course)