How to Find the Median of a List in Python
Compute the median of an unsorted numeric list using the statistics module in Python.
Python code
8 linesimport 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
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
- Implement manually: sort the list and pick the middle element or average two middle elements.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.