Median of a List

Probability and StatisticsEasy+10 XP+10

Median of a List

The median is the value sitting in the middle once the numbers are lined up in order. Half the list is below it, half above.

Task: write median(values) returning that middle value, rounded to 4 decimal places.

The two cases you have to handle:

  • An odd number of values has one true middle — line them up and take it.
  • An even number of values has no single middle, so take the average of the two middle values. For [2, 4, 7, 9] that's (4 + 7) / 2 = 5.5.

Also worth knowing:

  • values is never empty, and it arrives in no particular order — sort it yourself first, or "the middle" means nothing.
  • Work the position out from the list's length rather than reaching for statistics.median; the point is to see how the two cases differ.

The median only cares about position, never size — so a wildly large value at the end barely moves it.

Median Explorer

Visualize how sorting reveals the exact center of a dataset.

Find Middle
Dataset size: 0 (Even)
Sorting Result:Median = 0

Because the dataset has an even size (0), there is no single middle value. The two middle numbers are and — their average, ( + ) / 2 = 0, is the median.

Examples

values = [3, 1, 4, 1, 5]
returns 3.0
values = [7, 2, 9, 4]
returns 5.5

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run