Python Calculate the Average of a List
In Python, we can calculate the average of all elements in a list with simple code. First, we sum all elements in the list, then divide by the length of the list.
Example
def
calculate_average
(
numbers
)
:
return
sum
(
numbers
)
/
len
(
numbers
)
Example list
numbers
=
[
10
,
20
,
30
,
40
,
50
]
average
=
calculate_average
(
numbers
)
(
"The average of the list is:"
,
average
)
Code analysis:
calculate_averageThe function takes a listnumbersas its argument.sum(numbers)Calculate the sum of all elements in the list.len(numbers)Calculate the length of the list, i.e., the number of elements in the list.- Divide the sum by the list length to get the average and return this value.
- Example list
numberscontains five elements. - called
calculate_averagefunction calculates the average and prints the result.
Output result:
列表的平均值是: 30.0
Python3 Examples