Python sum() Function
sum() is a built-in function in Python used to sum the elements of an iterable.
sum() It is one of the most commonly used mathematical functions in Python, quickly computing the total of all elements in iterables such as lists, tuples and sets.
Word meaning: sum means "sum" and computes the total of a series of numbers.
Basic syntax and parameters
Syntax format
sum(iterable, start)
Parameter Description
- Parameter iterable:
- Type: iterable (list, tuple, set, etc.)
- Description: the iterable to sum.
- Parameter start(optional):
- Type: number
- Description: the starting value, defaulting to 0. It is added to the sum.
Function description
- Return Value: Returns the sum (an integer or a float).
- Requirement: The elements of the iterable must be numeric types (int, float).
Example
Example 1: basic usage
Example
Sum a list
numbers
=
[
1
,
2
,
3
,
4
,
5
]
result
=
sum
(
numbers
)
(
result
)
Output: 15
Sum a tuple
result
=
sum
(
(
10
,
20
,
30
)
)
(
result
)
Output: 60
Sum a set
result
=
sum
(
{
1
,
2
,
3
}
)
(
result
)
Output: 6
Sum a range
result
=
sum
(
range
(
1
,
101
)
)
(
result
)
Output: 5050 (the sum from 1 to 100)
Empty list
result
=
sum
(
[
]
)
(
result
)
Output: 0
Expected output:
15
60
6
5050
0
Code analysis:
- It supports various iterables such as lists, tuples, sets and ranges.
- The sum of an empty iterable defaults to 0.
Example 2: using the start parameter
Example
Set a starting value
numbers
=
[
1
,
2
,
3
]
The default is start=0
result
=
sum
(
numbers
)
(
result
)
Output: 6
Set start=10
result
=
sum
(
numbers
,
10
)
(
result
)
Output: 16 (6 + 10)
A negative starting value
result
=
sum
(
numbers
,
10
)
(
result
)
Output: -4 (6 + -10)
Useful when computing a cumulative total
scores
=
[
90
,
85
,
95
]
bonus
=
5
total
=
sum
(
scores
,
bonus
)
(
total
)
Output: 275 (90+85+95+5)
Expected output:
6
16
-4
275
Code analysis:
- The start parameter is added to the result after summing.
- It is often used to add a base score or bonus to a total.
Example 3: practical applications
Example
Compute an average
numbers
=
[
10
,
20
,
30
,
40
,
50
]
average
=
sum
(
numbers
)
/
len
(
numbers
)
(
f
"Average: {average}"
)
Output: Average: 30.0
Conditional sums
data
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
Sum the even numbers
even_sum
=
sum
(
x
for
x
in
data
if
x %
2
==
0
)
(
f
"Sum of even numbers: {even_sum}"
)
Output: Sum of even numbers: 30
Sum a dictionary (sum its values)
prices
=
{
'apple'
:
5
,
'banana'
:
3
,
'orange'
:
8
}
total_price
=
sum
(
prices.
values
(
)
)
(
f
"Total price: {total_price}"
)
Output: Total price: 16
Compute the sum of numbers from 1 to 100 divisible by 3 or 5
result
=
sum
(
x
for
x
in
range
(
1
,
100
)
if
x %
3
==
0
or
x %
5
==
0
)
(
result
)
Output: 2318
Expected output:
平均值: 30.0
偶数之和: 30
总价: 16
2318
sum() It is one of the most basic tools for handling numeric data; combined with list comprehensions it can implement complex conditional sums.
Python3 built-in function