Skip to content
UniCircle
EasyCodingDescriptive statistics

Mean, median, mode and standard deviation without libraries

Question DS-STA-101

Given n integer readings, compute these summary statistics without NumPy, pandas or the statistics module:

  • mean
  • median (the average of the two middle values when n is even)
  • mode (the most frequent value; if several values tie, the smallest)
  • population standard deviation, √(Σ(x − mean)² / n)
  • range (max − min)

Print mean, median and standard deviation with exactly 2 decimals.

Constraints

  • 1 ≤ n ≤ 10^4
  • −10^6 ≤ each value ≤ 10^6

Input and output

Input
First line: n. Second line: n integers.
Output
Five lines: `mean X`, `median X`, `mode X`, `std X`, `range X`.

Examples

Input 1

6
4 8 6 5 3 8

Output

mean 5.67
median 5.50
mode 8
std 1.89
range 5

Mean = 34/6 = 5.67. Sorted: 3 4 5 6 8 8, so the median is (5 + 6)/2 = 5.50. 8 appears twice. Range = 8 − 3 = 5.

Input 2

5
1 2 3 4 100

Output

mean 22.00
median 3.00
mode 1
std 39.01
range 99

One outlier pulls the mean up to 22.00, but the median stays at 3.00.

Show hints
  • Sort a copy of the data for the median.
  • A dict (or collections.Counter) gives the frequencies for the mode.
  • Population SD divides by n; sample SD divides by n − 1.
Show the explanation
Python
n = len(xs); s = sorted(xs)
mean = sum(xs) / n
median = s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2
freq = Counter(xs); top = max(freq.values())
mode = min(v for v, c in freq.items() if c == top)
std = math.sqrt(sum((x - mean) ** 2 for x in xs) / n)

Talking points

  • Population vs sample SD. Dividing by n describes this data set. Dividing by n − 1 (Bessel's correction) estimates the SD of the wider population that a sample came from. statistics.pstdev and statistics.stdev give the two versions. NumPy's np.std uses n by default (ddof=0), while pandas' Series.std() uses n − 1. Many people get caught by this difference.
  • Median vs mean. The median ignores how extreme the outliers are. Mean salary is pulled up by a few very large values; the median is not.
  • Mode is the only one of the three that also works for categorical data. Ties are common, so always state a tie rule.
  • Numerical care. The two-pass formula above (mean first, then squared deviations) is more accurate than the one-pass E[x²] − (E[x])², which can lose precision badly when values are large and close together. Welford's algorithm gives a stable one-pass version for streams.

Sorting dominates, so the cost is O(n log n). Quickselect can find the median in expected O(n).

Original UniCircle question. Last reviewed 22 Oct 2026.