Skip to content

Module 15 · Python Standard Libraries — topic 12 of 13

statistics

Descriptive statistics with the standard library: mean, median, mode, standard deviation and variance (sample and population), quantiles, correlation, linear regression and the normal distribution.

Beginner 10 min read·Lesson 233 of 306 in Python Programming

Learning objectives

  • Calculate averages and measures of spread
  • Distinguish sample and population statistics
  • Use quantiles, correlation, regression and NormalDist

Definition

statistics provides functions for calculating mathematical statistics of numeric data: averages, measures of spread, quantiles, correlation, simple linear regression and the NormalDist class.

Introduction

Class results, sales figures, sensor readings — you often need a quick summary. statistics gives accurate answers without installing anything.

Why it matters

Hand-written formulas are easy to get subtly wrong (sample vs population, even-length medians). The module handles these cases correctly.

Detailed explanation

mean is the average; median the middle value (average of the two middle values for even counts); mode the most common value. median_low/median_high and multimode cover special cases.

stdev and variance treat data as a sample (divide by n − 1); pstdev and pvariance treat it as the whole population (divide by n).

quantiles(data, n=4) returns cut points dividing data into n groups (quartiles for n=4).

correlation(x, y) gives Pearson's r between −1 and 1; linear_regression(x, y) returns the slope and intercept of the best-fit line.

NormalDist(mu, sigma) models a normal distribution; cdf(x) gives the probability of a value below x.

Empty data raises StatisticsError. Integer inputs may return Fractions or floats depending on the function.

For large datasets and advanced analysis, NumPy and pandas are faster, but statistics is perfect for everyday scripts.

Outliers affect statistics differently: one huge value pulls the mean a long way but barely moves the median, which is why median incomes are often reported instead of averages.

Syntax

Python
import statistics as st
st.mean(data), st.median(data), st.mode(data)
st.stdev(data)
st.quantiles(data, n=4)
slope, intercept = st.linear_regression(x, y)
  • Averages and spread.
  • Sample vs population functions.
  • Regression and distributions.

Code examples

Averages

Python
import statistics as st
marks = [72, 85, 91, 66, 85, 78]
print(st.mean(marks), st.median(marks), st.mode(marks))
Output
79.5 81.5 85

Spread

Python
import statistics as st
marks = [72, 85, 91, 66, 85, 78]
print(round(st.stdev(marks), 2), round(st.pstdev(marks), 2), st.variance([2, 4, 4, 4, 5, 5, 7, 9]))
Output
9.31 8.5 4.571428571428571

More examples

Quartiles, correlation and prediction

Python
import statistics as st
print(st.quantiles([66, 72, 78, 85, 85, 91], n=4))
hours = [1, 2, 3, 4, 5]
scores = [52, 60, 63, 71, 79]
r = st.correlation(hours, scores)
slope, intercept = st.linear_regression(hours, scores)
print(round(r, 3), slope, intercept)
print(f"predicted score for 6 hours: {slope * 6 + intercept}")
nd = st.NormalDist(mu=70, sigma=10)
print(round(nd.cdf(85), 4))
Output
[70.5, 81.5, 86.5]
0.991 6.5 45.5
predicted score for 6 hours: 84.5
0.9332

Step-by-step explanation

  • quantiles splits the marks into four groups and returns the three cut points.
  • A correlation near 1 means study hours and scores rise together; the regression line predicts 84.5 for 6 hours.
  • NormalDist.cdf gives the probability that a normally distributed score is below 85 (about 93%).

Expected output

Running “Quartiles, correlation and prediction” prints exactly:

TextOutput
[70.5, 81.5, 86.5]
0.991 6.5 45.5
predicted score for 6 hours: 84.5
0.9332

Practical applications

  • Summarising exam results or survey answers.
  • Simple forecasting from trends.

Best practices

  • Choose sample or population functions deliberately.
  • Handle StatisticsError for empty data.
  • Round results for display only.

Common mistakes

Using stdev for a whole population

Avoid

st.stdev(all_employees_salaries)

Prefer

st.pstdev(all_employees_salaries)

stdev assumes a sample and slightly overestimates for complete populations.

Important notes

  • Correlation doesn't prove causation — it only measures how closely two variables move together.

Key takeaways

  • mean, median and mode summarise data.
  • stdev/variance vs pstdev/pvariance.
  • quantiles, correlation, regression and NormalDist go further.

Try it yourself

  1. 1
    Summarise a list of daily temperatures with mean, median, min, max and stdev.
  2. 2
    Fit a line to monthly sales and predict the next month.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic