Find the median — the middle value of an ordered dataset. First sort the values by repeatedly picking the smallest remaining element (min-pick), then select the centre position. With an odd number of values the median is the exact middle element; with an even count it is the mean of the two middle values. By hand, min-pick makes the ordering visible step by step.

By hand

With the library

statistics.median handles both odd and even counts. np.median returns the same value as a float.

naive.py
values = [4, 8, 6, 13, 10, 6, 9]
remaining = list(values)
sv = []
while remaining:
    m = min(remaining)
    sv.append(m)
    remaining.remove(m)
n = len(sv)
median = sv[n // 2]
print('RESULT:', median)
library.py
import statistics
import numpy as np
from dalib.display import set_display
set_display()

values = [4, 8, 6, 13, 10, 6, 9]
median_stdlib = statistics.median(values)
median_numpy = float(np.median(values))
print('statistics.median:', median_stdlib)
print('np.median:        ', median_numpy)
print('RESULT:', median_stdlib)
statistics.median: 8
np.median:         8.0
RESULT: 8

Implementation notes

  • For even n, statistics.median averages the two middle values (returns a float if they differ). The naive sv[n // 2] picks the upper-middle element — add explicit even-n handling if exact parity with the library is required.
  • The median is robust to outliers: replacing 13 with 1000 leaves the result unchanged at 8. The mean would shift significantly.
  • Cross-reference: arithmetic-mean (this chapter) to see how the mean reacts to the same outlier.