How to calculate mean in python?

Mean, also known as average is the sum of all the terms divided by a number of terms. In other words, it is the average of all the numbers.

python-mean-calculation

Mean can be calculated using a loop, using sum() and len() functions, or by importing statistics module.

Calculating mean using sum() and len() functions

sum() and len() are inbuilt functions in python to calculate the sum and number of elements of a numeric data set respectively.

Consider a list num_list = [5, 3, 2, 8, 9, 1]. The value returned by sum() function is stored in a variable add and the value returned by function len() is stored in variable num_terms.

The variable add is divided by num_terms to get the mean value.

num_list = [5, 3, 2, 8, 9, 1]
add = sum(num_list)
num_terms = len(num_list)
mean = add / num_terms
print("The mean of all the terms is: ", mean )

Output

The mean of all the terms is:  4.666666666666667

Calculating mean by importing statistics module

Python supports a built-in module known as statistics, to calculate statistics of numeric data. statistics.mean() can be used to calculate the mean of numbers in a data set. The statistics module can be used with data set like lists, tuple, or sets.

import statistics
num_set = {5, 3, 2, 8, 9, 1}
avg = statistics.mean(num_set)
print("The mean of all the terms is: ", avg)

Output

The mean of all the terms is:  4.666666666666667

Calculating mean using for loop

Let us consider num_list = [5, 3, 2, 8, 9, 1]. A variable num_terms is initialized to '0', to count the number of terms. A for loop is used to iterate over the list num_list. After encountering every element the value is added to the variable add and num_terms is incremented by 1. The variable add is divided by num_terms to get the mean value.

num_list = [5, 3, 2, 8, 9, 1]
add = 0
num_terms = 0
for i in num_list:
    add += i
    num_terms += 1
mean = add / num_terms
print("The mean of all the terms is: ", mean )

Output

The mean of all the terms is:  4.666666666666667

Calculating mean by importing statistics module

Python supports a built-in module known as statistics, to calculate statistics of numeric data. statistics.mean() can be used to calculate the mean of numbers in a data set. The statistics module can be used with data set like lists, tuple, or sets.

import statistics
num = {5,3,2,8,9,1}
avg = statistics.mean(num)
print("The mean of all the terms is: ",avg)

Output

The mean of all the terms is:  4.666666666666667
If anything other than numeric values is present in the sequence as a TypeError Exception is raised.

For example,

num_list = [5, 3, 2, 8, 9, 1, "Hello"]
add = sum(num_list)
num_terms = len(num_list)
mean = add / num_terms
print("The mean of all the terms is: ", mean )

Output

 add = sum(num)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions