Standard library · 2 / 17 Theory

statistics: mean, median and deviation

The statistics module calculates the most common statistical measures of a list of numbers. With Python's built-in functions (sum, min, max, len) you can already do a lot, and statistics adds the rest.

What you already have without importing anything

grades = [7, 9, 5, 8, 6]

print(sum(grades))              # 35
print(min(grades), max(grades)) # 5 9
print(sum(grades) / len(grades))# 7.0

Mean, median and mode

import statistics

grades = [7, 9, 5, 8, 6, 7]

print(statistics.mean(grades))    # 7       the mean
print(statistics.median(grades))  # 7.0     the central value
print(statistics.mode(grades))    # 7       the most repeated value
  • The mean is the sum of the values divided by how many there are.
  • The median is the central value once the data is sorted. With an even amount, it is the mean of the two central ones.
  • The mode is the value that is repeated the most.
print(statistics.median([1, 2, 3, 4]))   # 2.5
print(statistics.median([1, 2, 100]))    # 2  (the median is not affected by the 100)
print(statistics.mean([1, 2, 100]))      # 34.333333333333336

That is why the median is more representative than the mean when there are extreme values.

Dispersion: standard deviation

The standard deviation tells you how far the data is from the mean. The larger it is, the more spread out the data is:

print(statistics.pstdev([5, 5, 5]))        # 0.0  all equal
print(statistics.pstdev([2, 4, 4, 4, 5, 5, 7, 9]))  # 2.0
print(statistics.stdev([2, 4, 4, 4, 5, 5, 7, 9]))   # 2.138089935299395
  • pstdev calculates the population deviation: the data is all the possible values.
  • stdev calculates the sample deviation: the data is only a sample of something bigger. It needs at least two values.

Common mistakes

statistics.mean([])
# StatisticsError: mean requires at least one data point

Always check that the list is not empty before calculating the mean or the median.

Formatting the result

mean = statistics.mean([1, 2, 2])
print(mean)           # 1.6666666666666667
print(f"{mean:.2f}")  # 1.67

Practice in Statistics summary.