Python Calculate the Average of a List

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. calculate_averageThe function takes a listnumbersas a parameter.
  2. sum(numbers)Calculate the sum of all elements in the list.
  3. len(numbers)Calculate the length of the list, i.e., the number of elements in the list.
  4. Divide the sum by the length of the list to get the average, and return that value.
  5. Example listnumbersContains five elements.
  6. Callcalculate_averagethe function to calculate the average, and print the result.

Output result:

列表的平均值是: 30.0

Document 对象参考手册Python3 Examples

Other extensions