Python Statistics
last modified November 29, 2026 Python 3.15
In this article we show how to use the statistics module from the
Python standard library to compute averages, measures of spread, quantiles,
correlation, and a regression line.
The module is written in pure Python and accepts any numeric type that supports
addition and division, including int, float, and
Decimal. When the input is Decimal, the results stay
exact instead of accumulating binary rounding errors. For very large arrays,
NumPy and Pandas are a better fit; see
Python Scipy Stats.
Mean
The mean, also called the arithmetic average, is the sum of all
values divided by their count. The mean function does exactly that,
so the first example computes the same number in two ways and compares them.
import statistics
data = [4, 8, 6, 5, 3, 7]
print(f"sum: {sum(data)}, count: {len(data)}")
mean = statistics.mean(data)
print(f"mean: {mean}")
With six values that add up to 33, the mean is 33 / 6, which is
5.5. The function accepts any iterable of numbers, not only a list,
and it raises StatisticsError when the data is empty because there
is nothing to divide by.
$ python mean.py sum: 33, count: 6 mean: 5.5
Float mean
The fmean function computes the same average but always returns a
float. It converts the input to floats and sums them with
math.fsum, which keeps rounding error small and makes it faster
than mean on large datasets. The price is precision: exact types
are lost.
import statistics
from decimal import Decimal
prices = [Decimal('1.10'), Decimal('2.20'), Decimal('3.30')]
print(statistics.mean(prices))
print(type(statistics.mean(prices)).__name__)
print(statistics.fmean(prices))
print(type(statistics.fmean(prices)).__name__)
Both functions return 2.2 in value, but only mean
keeps the Decimal type and prints the exact 2.2. The
fmean result is a binary float, so the stored value is the closest
double to 2.2 and is displayed with all its digits.
$ python fmean.py 2.2 Decimal 2.1999999999999997 float
Median
The median is the middle value of the sorted data. Unlike the mean, it is not pulled away by a single extreme value. When the count is even, there is no single middle element, and the module offers three ways to pick one.
import statistics readings = [12, 7, 3, 15, 9, 4] print(statistics.median(readings)) print(statistics.median_low(readings)) print(statistics.median_high(readings)) odd = [12, 7, 3, 15, 9] print(statistics.median(odd))
Sorted, the six readings are 3, 4, 7, 9, 12, 15. The median is the
average of the two middle values, (7 + 9) / 2 = 8.0;
median_low returns the lower of them (7) and
median_high the upper one (9). With an odd count the
middle value is returned directly, here 9.
$ python median.py 8.0 7 9 9
Mode
The mode is the most frequent value in the data. The
mode function returns a single value. When several values tie for
the highest frequency, it returns the first one it meets, so use
multimode if you need to see all of them. Only empty data makes
mode raise StatisticsError.
import statistics votes = ['anna', 'carl', 'anna', 'bob', 'bob', 'anna'] print(statistics.mode(votes)) print(statistics.mode(['red', 'green', 'green', 'red'])) print(statistics.multimode(votes)) print(statistics.multimode(['red', 'blue', 'blue', 'green', 'green']))
Anna received three votes, Bob two, and Carl one, so mode returns
anna. In the tie between red and green it returns
red, the value that appears first. The two multimode
calls return a one-element list for the votes and both tied colours for the
second list. The mode works on strings and other hashable values, not only on
numbers.
$ python mode.py anna red ['anna'] ['blue', 'green']
Variance and standard deviation
The variance measures how far the values spread around the mean. It is the average of the squared distances from the mean, so its unit is the square of the original unit. The standard deviation is its square root, which brings the result back to the original unit.
The module provides two versions of each. variance and
stdev divide by n - 1 and are used when the data is a
sample of a larger population. pvariance and pstdev
divide by n and describe the data as the whole population.
import statistics
temps = [21.5, 22.0, 21.0, 23.5, 22.5, 21.5, 22.0]
print(f"sample variance: {statistics.variance(temps):.4f}")
print(f"population variance: {statistics.pvariance(temps):.4f}")
print(f"sample stdev: {statistics.stdev(temps):.4f}")
print(f"population stdev: {statistics.pstdev(temps):.4f}")
The seven readings have a mean of exactly 22.0 and a sum of squared
deviations of 4.0. Dividing by n - 1 = 6 gives
0.6667, and dividing by n = 7 gives
0.5714. The standard deviations are the square roots of those
numbers, in degrees like the input. Unless all values are equal, the sample
values are slightly larger, and the difference shrinks as the dataset grows.
$ python variance.py sample variance: 0.6667 population variance: 0.5714 sample stdev: 0.8165 population stdev: 0.7559
Quantiles and outliers
Quantiles cut sorted data into equal-sized intervals. With
n=4 we get quartiles: Q1 at 25%, Q2 (the median) at 50%, and Q3 at
75%. The interquartile range (IQR) is Q3 - Q1 and
covers the middle half of the data. Values farther than
1.5 * IQR below Q1 or above Q3 are commonly treated as outliers.
The quantiles function uses a method to interpolate between data
points. The default, exclusive, assumes the data is a sample from a
larger population; inclusive treats the dataset as the whole
population. We use the second one below.
import statistics
data = [10, 12, 12, 14, 12, 11, 14, 13, 15, 100]
q1, q2, q3 = statistics.quantiles(data, n=4, method='inclusive')
print(f"Q1: {q1}, Q2: {q2}, Q3: {q3}")
iqr = q3 - q1
low = q1 - 1.5 * iqr
high = q3 + 1.5 * iqr
print(f"IQR: {iqr}, bounds: {low} .. {high}")
clean = [x for x in data if low <= x <= high]
print(clean)
The quartiles are 12.0, 12.5, and 14.0,
so the IQR is 2.0 and the allowed range is
9.0 to 17.0. Only the value 100 falls
outside, and the list comprehension removes it. The remaining nine values are
the typical readings.
$ python quantiles.py Q1: 12.0, Q2: 12.5, Q3: 14.0 IQR: 2.0, bounds: 9.0 .. 17.0 [10, 12, 12, 14, 12, 11, 14, 13, 15]
Geometric and harmonic mean
Not every average is arithmetic. The geometric mean multiplies the values and takes the n-th root; it suits growth factors and ratios. The harmonic mean divides the count by the sum of the reciprocals; it suits rates such as speeds over equal distances.
import statistics growth = [1.0, 1.5, 2.0] print(statistics.geometric_mean(growth)) speeds = [60, 40] print(statistics.harmonic_mean(speeds))
The product of the growth factors is 3.0, and its cube root is
about 1.4422, meaning the same total growth in three equal steps.
A car that drives 60 km/h one way and 40 km/h back averages
2 / (1/60 + 1/40) = 48 km/h, not 50, because it spends more time at
the slower speed.
$ python other_means.py 1.4422495703074083 48.0
Correlation
Correlation measures how strongly two variables move together.
By default correlation computes the Pearson coefficient, usually
written r, which describes a linear relationship. It ranges from
-1 (perfect negative) through 0 (no linear
relationship) to +1 (perfect positive).
With method='ranked' the values are replaced by their ranks first,
which gives the Spearman coefficient. It measures a monotonic relationship: the
two variables rise and fall together, even if not at a constant rate.
import statistics
period = [88, 225, 365, 687, 4331, 10_756, 30_687, 60_190] # days
dist = [58, 108, 150, 228, 778, 1_400, 2_900, 4_500] # million km
print(f"Pearson: {statistics.correlation(period, dist):.4f}")
print(f"Spearman: {statistics.correlation(period, dist, method='ranked')}")
The two lists hold the orbital period and the distance from the Sun for the
first eight planets. The Pearson coefficient is 0.9882: the points
lie close to a straight line, but not exactly on it. The ranked coefficient is
1.0, because the planets are already ordered by both values, a
perfect monotonic relationship. Neither number says that one variable causes
the other.
$ python correlation.py Pearson: 0.9882 Spearman: 1.0
Linear regression
Linear regression fits the straight line that minimizes the
squared distances to the data points. The linear_regression
function returns a named tuple with the slope and
intercept of that line, following the equation
y = slope * x + intercept.
import statistics
hours = [1, 2, 3, 4, 5, 6, 7, 8]
score = [42, 48, 55, 61, 66, 74, 79, 86]
model = statistics.linear_regression(hours, score)
print(model)
print(f"slope: {model.slope:.2f}, intercept: {model.intercept:.2f}")
print(f"score after 10 hours: {model.slope * 10 + model.intercept:.1f}")
Each extra hour of study is associated with about 6.25 more points,
and at zero hours the line predicts 35.75. The prediction for ten
hours is 98.2 points, obtained by evaluating the line at
x = 10. Pass proportional=True when the line should
pass through the origin; the intercept is then zero.
$ python regression.py LinearRegression(slope=6.25, intercept=35.75) slope: 6.25, intercept: 35.75 score after 10 hours: 98.2
Normal distribution
The NormalDist class represents a normal (Gaussian) distribution
defined by its mean mu and standard deviation
sigma. Its cdf method gives the probability that a
value is less than or equal to a point, and inv_cdf answers the
opposite question: which value has a given probability below it.
import statistics
iq = statistics.NormalDist(mu=100, sigma=15)
print(f"P(x <= 115): {iq.cdf(115):.4f}")
print(f"P(x > 130): {1 - iq.cdf(130):.4f}")
print(f"top 10%: {iq.inv_cdf(0.90):.2f}")
sample = statistics.NormalDist.from_samples([98, 102, 97, 105, 99])
print(f"sample mean: {sample.mean}, stdev: {sample.stdev:.4f}")
An IQ of 115 is one standard deviation above the mean, and the probability of
scoring at most 115 is about 0.8413. Scoring above 130 happens with
probability 0.0228, and the top ten percent starts at about
119.22. The from_samples class method builds a
distribution from raw data using the sample mean and sample standard
deviation.
$ python normal.py P(x <= 115): 0.8413 P(x > 130): 0.0228 top 10%: 119.22 sample mean: 100.2, stdev: 3.2711
Errors and edge cases
Most functions raise StatisticsError when there is not enough data:
mean needs at least one value and stdev at least two.
Special float values are handled inconsistently: a single nan
makes mean and median return nan, while
stdev and pstdev raise ValueError for
nan and infinity.
import statistics
try:
statistics.mean([])
except statistics.StatisticsError as e:
print(f"StatisticsError: {e}")
try:
statistics.stdev([5])
except statistics.StatisticsError as e:
print(f"StatisticsError: {e}")
print(statistics.mean([1.0, float('nan'), 3.0]))
The messages name both the function and the requirement, which makes them easy
to recognize in a traceback. Filtering out invalid values before the
calculation is usually better than letting a nan silently spread
through every result.
$ python errors.py StatisticsError: mean requires at least one data point StatisticsError: stdev requires at least two data points nan
Source
statistics – Mathematical statistics functions – Python documentation
decimal – Decimal fixed point and floating point arithmetic – Python documentation
In this article we have computed means, medians, modes, variance, standard
deviation, quantiles, correlation, and a regression line with the Python
statistics module. See also
Python Decimal,
Python random module, and
Python Scipy Stats.
Author
List all Python tutorials.