A salary benchmarking sheet has a few very large outliers, so the mean is misleading. You need the median instead — and the interviewer wants it implemented by hand.
Write a function median(values) that returns the median of a list of numbers as a float, without importing statistics or numpy. Return None for an empty list.
This fixture runs before your code on every Run and Submit, so the data is always clean.
salaries = [420000, 610000, 550000, 4800000, 505000, 720000]- Step 1: Handle the empty list up front — there is no middle value to return.
- Step 2: `sorted(values)` returns a **new** sorted list, so the caller's data is not mutated. `values.sort()` would modify it in place, which is a common interview trap.
- Step 3: `mid = n // 2` uses integer division to find the middle index.
- Step 4: For an odd count the single middle element is the median; cast to `float` so the return type is consistent.
- Step 5: For an even count, average the two central elements. `/` always produces a float in Python 3.
def median(values):
if not values:
return None
ordered = sorted(values)
n = len(ordered)
mid = n // 2
if n % 2 == 1:
return float(ordered[mid])
return (ordered[mid - 1] + ordered[mid]) / 2Learn the concept first
Stuck on Statistics? These free Python lessons teach it step by step.
More Statistics questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program