How to calculate the average (arithmetic mean) from a list of numbers in python ?


Examples of how to calculate the average (arithmetic mean) from a list of numbers in python:

Let's consider the following list

l = [5, 3, 2, 9, 1, 4]

to calculate the mean, there are several solutions:

Note: here the mean is based on the following estimator:

\begin{equation}
\hat{\mu} = \frac{1}{n} \sum x
\end{equation}

Calculate the mean with the python module statistics

To calculate the mean from a list, a solution is to use the python module statistics, example:

from statistics import mean

l_mean = mean(l)

print(l_mean)

returns

4.0

Calculate the mean with numpy

Another solution using numpy:

import numpy as np

l_mean = np.mean(np.array(l))

print(l_mean)

returns

4.0

Calculate the mean with sum() et len()

l_mean = sum(l) / len(l)

print(l_mean)

returns

4.0

Calculate the mean with a for loop

Another example using a for loop

a = 0
b = 0
for i in l:
    a += i
    b += 1

l_mean = float(a) / b

print(l_mean)

returns

4.0

Create a function to calculate the mean

def calculate_mean_from_list(list):
    return sum(list) / len(list)

calculate_mean_from_list(l)

returns

4.0

Check that the list contains only numbers

Note: to be sure that the list contains only numbers a solution is to use the function isinstance(), illustration:

l = [i for i in l if isinstance(i, (int, float))]

References