Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

How to Find the Median of a List in Python

Learn how to calculate the median of a list in Python, including step-by-step explanations and code snippets. …


Updated June 25, 2023

Learn how to calculate the median of a list in Python, including step-by-step explanations and code snippets.

Definition of the Concept

The median is the middle value in a set of numbers when they are arranged in ascending or descending order. If there is an even number of values, the median is the average of the two middle values.

In this article, we will focus on finding the median of a list in Python, which involves arranging the list in order and then selecting the middle value(s).

Step-by-Step Explanation

Here’s how to find the median of a list in Python:

Step 1: Import the statistics Module

The most straightforward way to calculate the median is by using the statistics.median() function from Python’s built-in statistics module. To use this function, you need to import it first.

import statistics

Step 2: Create a List of Numbers

For demonstration purposes, let’s create a list of numbers:

numbers = [1, 3, 5, 7, 9]

Step 3: Use the median() Function to Calculate the Median

Now that we have our list of numbers, we can use the statistics.median() function to calculate the median:

median_value = statistics.median(numbers)
print(median_value)  # Output: 5

Alternative Method Using Sorting

While using the statistics module is efficient, you might want to understand how the median is calculated manually. Here’s an alternative method that involves sorting the list and then selecting the middle value(s):

numbers = [1, 3, 5, 7, 9]

# Sort the list in ascending order
numbers.sort()

# Find the length of the list
n = len(numbers)

# If there is an odd number of values, select the middle value
if n % 2 == 1:
    median_value = numbers[n // 2]
else:  # If there is an even number of values, average the two middle values
    median_value = (numbers[n // 2 - 1] + numbers[n // 2]) / 2

print(median_value)  # Output: 5

Conclusion

Finding the median of a list in Python can be achieved efficiently using the statistics.median() function or by manually sorting the list and selecting the middle value(s). Both methods are presented in this article, along with code snippets for demonstration purposes.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp