Stats calculator: mean and variance
The mean is the plain average: add everything up, divide by how many there
are - sum(nums) / len(nums). No import needed; sum and len are
built-ins.
Variance measures how spread out the numbers are around that mean. The
population variance - the simpler of the two variance formulas, and the
one this lesson uses - is the average of the squared distance from each
number to the mean: for every x in nums, compute (x - mean) ** 2, then
average those. Squaring keeps distances positive (so numbers below the mean
don't cancel out ones above it) and exaggerates the numbers that are furthest
from it.
Your task: write mean(nums), returning the arithmetic mean of the
numbers in nums. Then write variance(nums), returning the population
variance - the average of (x - mean(nums)) ** 2 across every x in nums.
You'll practice:
Computing an average with sum and len
Building the variance formula from a generator expression and a call to
your own mean
Show a hint
Show solution
Related reading: Reading Data: Statistics That Don't Lie →
Previous Next