Sample Variance

Probability and StatisticsEasy+10 XP+10

Sample Variance

Variance measures how spread out a list of numbers is. A tight cluster gives a small variance; numbers scattered all over give a large one.

You build it in three moves:

  1. Find the mean.
  2. Take each value's distance from the mean and square it.
  3. Average those squared distances.

Task: write sample_variance(values) returning that average, rounded to 4 decimal places.

There is one catch, and it is the entire point of this problem: in step 3, divide by n - 1, not by n.

  • Dividing by n - 1 gives the sample variance — the right choice when your list is a sample drawn from some larger population you can't fully see, which is nearly always the case. Dividing by n would quietly underestimate the real spread.
  • values always holds at least two numbers, so n - 1 is never zero.
  • Squaring is what keeps every distance positive. Without it the distances above and below the mean would cancel out and you'd get 0 every time.

Variance Explorer

Visualize signed deviations, squaring, and the step-by-step calculation of variance.

Why Square?
μ = 0
0
2
4
6
8
10
12
How Squaring Transforms Deviations

Why square? 1. Non-negativity: Squaring turns negative deviations into positive values (e.g. -4² = +16), preventing them from cancelling.

2. Outlier Amplification: Squaring increases values nonlinearly. A deviation of 2 creates a square of area 4, but a deviation of 4 creates an area of 16 (four times larger!). This places heavy penalties on values farther from the mean.

Examples

values = [2, 4, 4, 4, 5, 5, 7, 9]
returns 4.5714
values = [5, 5, 5, 5]
returns 0.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run