Skip to content
Choose an observed middle value with median_low or median_high

Choose an observed middle value with median_low or median_high

November 22, 2026

A middle value used as a discrete setting may need to come from the observed settings. Averaging the two middle observations can produce a value that was never used.

Run the example

Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Save this as demo_python_median_low_high_observed_values.py. Use that filename to avoid shadowing a standard-library module.

from statistics import median, median_low, median_high, StatisticsError

for settings in ([1, 2, 8, 16], [1, 2, 8]):
    print(f"{settings}: median={median(settings)}, low={median_low(settings)}, high={median_high(settings)}")

try:
    median_low([])
except StatisticsError:
    print("empty settings: rejected")

Run it:

python3 demo_python_median_low_high_observed_values.py

Output:

[1, 2, 8, 16]: median=5.0, low=2, high=8
[1, 2, 8]: median=2, low=2, high=2
empty settings: rejected

With an even number of observations, the low and high variants choose the lower and upper middle observations respectively. With an odd count they agree. Here the ordinary median of the even-sized sample is five, while the observed middle settings are two and eight.

Input policy and limits

Choosing the lower or upper middle observation is an application policy, not a guarantee about capacity or safety. Validate allowed settings separately, handle missing observations, and reject or remove NaNs before ordering numeric data. These functions describe the middle of the observations; they do not find the most frequent setting.

Clean up

In the same Bash session, remove the source file and the empty working directory:

rm -- demo_python_median_low_high_observed_values.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its contents before deleting anything else.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on