Neural Mastery
← Back to Practice

Sample Mean and Variance From Scratch

Difficulty: Easy · Concept: Probability & Statistics — Expectation, Variance, Covariance

For a dataset x1,,xnx_1, \dots, x_n, the mean is xˉ=1nixi\bar{x} = \frac{1}{n}\sum_i x_i, and the population variance is the average squared deviation from that mean: σ2=1ni(xixˉ)2\sigma^2 = \frac{1}{n}\sum_i (x_i - \bar{x})^2. Every summary statistic on this site — standard deviation, standardization/z-scores, the Gaussian assumption behind MSE — builds on these two numbers.

Your task: implement sample_mean_and_variance(data), returning a (mean, variance) tuple. Use the population definition above (divide by nn, not n1n-1).

Implement it yourself
assert sample_mean_and_variance([2, 4, 4, 4, 5, 5, 7, 9]) == (5.0, 4.0) assert sample_mean_and_variance([1, 1, 1, 1]) == (1.0, 0.0) assert sample_mean_and_variance([1, 2, 3, 4, 5]) == (3.0, 2.0) assert sample_mean_and_variance([10]) == (10.0, 0.0)

Next: Standardize a Dataset (Z-Score Normalization) (a harder variant), or skip ahead to Bayes' Theorem: Posterior From Scratch

Last updated Sep 5, 2026Edit this pageReport an issue