Python 3.4+statisticsfunction
statistics.median
median
The median: the middle value of sorted data (for an even length, the mean of the two middle values).
Syntax
statistics.median(data)
You do not need to sort the data first — median() sorts internally, which is where its O(n log n) cost comes from. On an even-length sample it averages the two middle values, so the answer can be fractional and need not occur in the data at all; when you need a value that genuinely exists in the sample, reach for median_low() or median_high(). Empty input raises StatisticsError rather than returning zero or None.
Examples
import statistics
print(statistics.median([1, 2, 3, 4])) # → 2.5
print(statistics.median([1, 3, 5])) # → 3
print(statistics.median([5, 1, 4, 2])) # → 3.0
print(statistics.median([1, 2, 3, 4, 100])) # → 3
print(statistics.median([])) # → StatisticsError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy