Batu Lab NotesPractical developer guides

Use median_low for a discrete middle choice

By Batu ยท English technical notes

Also published in our Blogger archive.

A priority list can have an even number of discrete choices, where an averaged middle value would be meaningless. For example, a rank of 2.5 cannot identify a ranked item when valid ranks are whole numbers. statistics.median_low() accepts unsorted numeric data and returns the middle item for odd-sized data, or the smaller of the two central items for even-sized data.

Here, four issue ranks arrive unsorted. The lower middle is rank 2, not the interpolated median 2.5. The assertions check both the selected value and the important discrete-data property: the answer is one of the supplied ranks. The printed result makes the selection explicit for a small command-line report.

Do not mistake this rule for a universal definition of a median. Choosing the lower middle is a policy decision; median_high() chooses the upper central observation, while median() averages numeric middle values. Empty input raises StatisticsError, and NaN values can make sorting-based statistics surprising, so validate missing or non-finite measurements before applying the function. The statistics module, including median_low(), was added in Python 3.4. The official documentation describes its actual-data-point behavior and even-length rule in the Python statistics documentation.

AI assistance disclosure: this article was drafted with AI assistance and its example was synthetically tested.

from statistics import median_low

ranks = [4, 1, 3, 2]
choice = median_low(ranks)

assert choice == 2
assert choice in ranks

print(f"lower-middle rank: {choice}")
lower-middle rank: 2