To get the mean in Python, call statistics.mean(numbers) on a list, or numpy.mean(array) on a NumPy array. Python has no built-in mean() function, so you import one of these or write sum(numbers) / len(numbers) yourself.
from statistics import mean
scores = [2, 4, 4, 4, 5, 5, 7, 9]
print(mean(scores)) # 5
The mean is the sum of the values divided by how many there are: here 40 / 8 = 5. The rest of this article covers the four ways to compute it, when to pick each, and the cases that trip people up: empty data, NaN values, outliers and weights.
Which function should you use?
| Function | Works on | Returns | Use it when |
|---|---|---|---|
sum(x) / len(x) | Any list or tuple | float | You want no import and the data is never empty |
statistics.mean(x) | Sequence or iterable | Same type as the data | You want exact results with Fraction or Decimal |
statistics.fmean(x) | Sequence or iterable | Always float | You want speed, or weights |
numpy.mean(a) | Arrays, nested lists | ndarray or NumPy scalar | You have a 2D array or large numeric data |
statistics.mean(): the standard library answer
The statistics module ships with Python (added in 3.4), so there is nothing to install. According to the Python documentation, mean(data) returns the sample arithmetic mean of a sequence or iterable. These are the documentation's own examples:
from statistics import mean
mean([1, 2, 3, 4, 4]) # 2.8
mean([-1.0, 2.5, 3.25, 5.75]) # 2.625
from fractions import Fraction as F
mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) # Fraction(13, 21)
from decimal import Decimal as D
mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]) # Decimal('0.5625')
The last two lines show why mean() exists next to the plain division approach. It returns a value of the same kind as your data instead of forcing everything into a float, so decimal money amounts stay decimal.
If the data is empty, mean() raises StatisticsError. The plain version, sum([]) / len([]), raises ZeroDivisionError instead. Both are programmer-visible failures rather than a silent wrong answer, so decide where an empty list can occur and handle it there:
from statistics import mean, StatisticsError
def safe_mean(values):
try:
return mean(values)
except StatisticsError:
return None
statistics.fmean(): faster, always a float
fmean() converts the data to floats and computes the mean. The documentation says it runs faster than mean() and always returns a float. It was added in Python 3.8.
from statistics import fmean
fmean([3.5, 4.0, 5.25]) # 4.25
Since Python 3.11, fmean() takes a second argument, weights, for a weighted mean. The weights must have the same length as the data, or you get a ValueError. The documentation example weights four grades:
grades = [85, 92, 83, 91]
weights = [0.20, 0.20, 0.30, 0.30]
fmean(grades, weights) # 87.6
That is (85 x 0.20 + 92 x 0.20 + 83 x 0.30 + 91 x 0.30) / 1.0 = 87.6. On Python 3.10 or older, passing weights fails, so check your version with python --version first.
numpy.mean(): arrays and axes
NumPy is a third-party package (pip install numpy). Its numpy.mean(a, axis=None, dtype=None, out=None, keepdims=..., *, where=...) averages an array. With the default axis=None it averages the whole array after flattening it. These examples come from the NumPy reference page:
import numpy as np
a = np.array([[1, 2], [3, 4]])
np.mean(a) # 2.5
np.mean(a, axis=0) # array([2., 3.]) one mean per column
np.mean(a, axis=1) # array([1.5, 3.5]) one mean per row
A common mix-up is which way axis points. axis=0 collapses the rows, so you get one value for each column. axis=1 collapses the columns, so you get one value for each row. If you set keepdims=True, the reduced axis stays with size one, which lets the result broadcast against the original array, for example when subtracting each row's mean.
The where argument (added in NumPy 1.20.0) picks which elements count:
a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
np.mean(a) # 12.0
np.mean(a, where=[[True], [False], [False]]) # 9.0
Only the first row (5, 9, 13) is included in the second call, and 27 / 3 = 9.0.
Precision with float32
For integer input, NumPy computes the mean in float64. For floating-point input it uses the input's own precision, and the docs warn this can be inaccurate, especially for float32. The documentation's example averages 524,288 float32 values that should average 0.55:
a = np.zeros((2, 512*512), dtype=np.float32)
a[0, :] = 1.0
a[1, :] = 0.1
np.mean(a) # np.float32(0.54999924)
np.mean(a, dtype=np.float64) # 0.55000000074505806 (the docs mark this "may vary")
If you average large float32 arrays, pass dtype=np.float64.
Mean of a list with NaN values
numpy.mean() returns nan if any element is nan, because the sum becomes nan. Use numpy.nanmean() to skip them. Per the NumPy docs it divides the sum of the non-NaN elements by the number of non-NaN elements:
a = np.array([[1, np.nan], [3, 4]])
np.nanmean(a) # 2.6666666666666665 (1 + 3 + 4) / 3
np.nanmean(a, axis=0) # array([2., 4.])
If a slice contains only NaN, nanmean() returns NaN and raises a RuntimeWarning.
The statistics module has no NaN handling. Its documentation shows that median() on data containing NaN gives an unexpected result, and recommends stripping the NaN values first. Do the same before calling mean() or fmean():
from itertools import filterfalse
from math import isnan
clean = list(filterfalse(isnan, data))
When the mean misleads: outliers and the median
The Python documentation notes that the mean is strongly affected by outliers and points to median() as a measure that outliers affect less. A small example you can check by hand, with page load times in milliseconds:
from statistics import mean, median
times = [10, 12, 11, 13, 500]
mean(times) # 109.2
median(times) # 12
One slow request drags the mean to 109.2 ms, although four of the five values are within 3 ms of 12 ms. For an even number of values, median() averages the two middle ones, so median([1, 3, 5, 7]) is 4.0.
Other kinds of mean
The arithmetic mean is not always the right average. The statistics module has two more, both documented with examples:
geometric_mean()(Python 3.8+) suits growth rates and ratios.round(geometric_mean([54, 24, 36]), 1)gives36.0. It raisesStatisticsErrorfor empty data, zero, or negative values.harmonic_mean()suits rates such as speed over equal distances.harmonic_mean([40, 60])gives48.0, not 50. It acceptsweightsfrom Python 3.10.
If you want the most frequent value instead of an average, use statistics.mode(). Since Python 3.8 it returns the first one encountered when several values tie.
If you get an error
ModuleNotFoundError: No module named 'numpy': NumPy is not installed in the interpreter you are running. Install it into the same environment withpython -m pip install numpy.TypeErroron a list of strings: data read from a file or input is text. Convert it first, for example[float(item) for item in items].statistics.meanorfmeanraisesStatisticsError: the input is empty. Check how the list was built.nanas the result: a NaN is in the data. Clean it, or usenumpy.nanmean().
Frequently asked questions
- What is the difference between mean() and fmean() in Python?
- statistics.mean() keeps the type of your data, so Fractions give a Fraction and Decimals give a Decimal. statistics.fmean() converts everything to float, runs faster, and always returns a float. fmean() was added in Python 3.8, and it accepts weights from Python 3.11.
- How do I find the mean of a list in Python without importing anything?
- Divide the sum by the length: sum(numbers) / len(numbers). It fails with ZeroDivisionError on an empty list, so check for an empty list first. The statistics module does the same job and raises StatisticsError on empty data instead.
- Does numpy.mean() ignore NaN values?
- No. If any value is NaN, numpy.mean() returns NaN. Use numpy.nanmean(), which divides the sum of the non-NaN values by the count of non-NaN values. If every value is NaN, it returns NaN and raises a RuntimeWarning.
- How do I get the mean of each column in a NumPy array?
- Pass axis=0 to numpy.mean(). axis=0 averages down the rows and gives one value per column, while axis=1 averages across each row and gives one value per row. With the default axis=None, NumPy averages the whole flattened array into a single number.