Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Calculate the Average of a List

Python Calculate the Average of a List

Document Object Reference Manual Python3 Examples

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

)

print

(

"The average of the list is:"

,

average

)

Code analysis:

  1. calculate_average The function takes a list numbers as its argument.
  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 list length to get the average and return this value.
  5. Example list numbers contains five elements.
  6. called calculate_average function calculates the average and prints the result.

Output result:

列表的平均值是: 30.0

Document Object Reference Manual Python3 Examples