Spread of a Number List: Population Variance
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Implement population variance on a list of numbers without external libraries, handling empty and single-element inputs and choosing a numerically sound approach.
Measuring Spread
You are given a list of numbers (integers and/or floats). Write a function that returns how spread out the values are, measured as the population variance. Do not use external libraries such as NumPy or pandas.
Definition
Let n be the number of values and mu their arithmetic mean. The population variance is the average of the squared distances from the mean:
variance = (1 / n) * sum((x - mu)^2 for each x in the list)
Divide by n, not by n - 1.
Rules
- Empty list: the variance is undefined, so raise a
ValueError. - One element: return
0.0, since the single value equals its own mean. - Mixed numeric types: ints and floats may appear together. The result is a float (or a value equal to one, such as
2.0for2). - Return the variance as a single number.
Constraints
0 <= len(values) <= 10^5- Each element is a finite int or float.
- The input is a list, so it may be traversed more than once.
- Aim for
O(n)time andO(1)extra space. - Prefer subtracting the mean before squaring, rather than computing
E[x^2] - E[x]^2, to avoid loss of precision when values are large and close together.
Examples
Example 1
Input: population_variance([1, 2, 3, 4, 5])
Output: 2
Example 2
Input: population_variance([4, 4, 4])
Output: 0
Example 3
Input: population_variance([2])
Output: 0
Hints
Hint 1
Start by computing the mean: the sum of the values divided by how many there are.
Hint 2
The variance is the average of the squared differences between each value and that mean. Divide by n, not n - 1.
Hint 3
Check for an empty list first and raise ValueError. Use a generator expression inside sum so no extra list is built.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use the two-pass method, which follows the definition directly.
- If the list is empty, raise
ValueErrorbefore doing any division. - First pass: compute the mean as
sum(values) / n. - Second pass: sum the squared deviations
(x - mean) ** 2and divide byn.
Why it is correct
- The first pass gives the mean
mu(up to floating-point rounding). - The second pass visits each element once and computes the sum of
(x - mu)^2. - Dividing by
ngives the population variance by definition. - A single element equals its mean, so its deviation is zero and the result is
0.0. - The empty-list guard means we never divide by zero.
The shortcut formula E[x^2] - (E[x])^2 is algebraically equivalent but can suffer catastrophic cancellation when values are large and tightly clustered. Subtracting the mean first keeps the numbers small and accurate.
Complexity
- Time:
O(n), two linear passes. - Space:
O(1)extra, since the generator expression produces one squared deviation at a time and builds no intermediate list.
Reference solution
from typing import List
def population_variance(values: List[float]) -> float:
if not values:
raise ValueError("variance requires at least one value")
n = len(values)
mean = sum(values) / n
return sum((value - mean) ** 2 for value in values) / n