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 need to sum all the 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)
print("The average of the list is:", average)
return sum(numbers) / len(numbers)
# Example list
numbers = [10, 20, 30, 40, 50]
average = calculate_average(numbers)
print("The average of the list is:", average)
Code explanation:
calculate_averageThe function takes a listnumbersas a parameter.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 length of the list to get the average, and return that value.
- Example list
numbersContains five elements. - Call
calculate_averagethe function to calculate the average, and print the result.
Output result:
列表的平均值是: 30.0Other extensions
Python3 Examples