How to Find the Median of a List in Python

Compute the median of an unsorted numeric list using the statistics module in Python.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 12 views 0 copies

Python code

8 lines
Python 3.9+
import statistics

def median_of_list(numbers):
    return statistics.median(numbers)

if __name__ == "__main__":
    sample = [7, 3, 1, 4, 9, 2, 8]
    print(median_of_list(sample))

Output

stdout
4

How it works

The statistics.median function sorts the list internally and returns the middle value for odd-length lists or the average of the two middle values for even-length lists. This function handles both integer and float inputs, and raises StatisticsError for empty lists. Using the standard library avoids reinventing the wheel and keeps the code concise. For large lists, the O(n log n) sorting is acceptable in most use cases.

Common mistakes

  • Forgetting to handle the empty list case, which raises StatisticsError.
  • Assuming the list is already sorted and returning the element at index len//2 without sorting.
  • Using the mean instead of the median, which gives a different result for skewed distributions.

Variations

  1. Implement manually: sort the list and pick the middle element or average two middle elements.
  2. Use numpy.median for large arrays and arrays with NaN values.

Real-world use cases

  • Calculating household income median from survey responses to report economic trends.
  • Determining the median latency of API requests to set performance baselines.
  • Finding the median house price in a neighborhood for market analysis reports.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.