How To Find The Median Of A List In Python

In this tutorial, we will learn how to find the median of a list in Python. The median is the value that separates a list or array of ordered numbers into two halves, where half the numbers are either greater or equal to the median value, and half the numbers are less than or equal.

It’s a very useful statistical measurement, especially when dealing with large datasets, as it provides a relatively stable center value that is less affected by extreme values (unlike the mean).

Python makes it easy to find the median using various methods, which we will discuss in this tutorial.

Step 1: Create a Sample List

First, we need to create a sample list of numbers for which we want to find the median. You can manually create a list or generate it using list comprehension or other methods. In this tutorial, we’ll create a simple list of integers.

Step 2: Sort the List

The median calculation requires an ordered list of numbers. So the next step is to sort our list. We can use the built-in sorted() function or the list sort() method.

Both methods will return the same sorted list:

Step 3: Find the Median

Now that we have a sorted list, we can find the median. The calculation depends on whether the length of the list is odd or even.

If the length of the list is odd, the median is the middle value of the list.

If the length of the list is even, the median is the average of the two middle values.

We can compute the median using some simple Python code:

In our example, the length of the list is 9 (odd), so the output will be the middle value:

Step 4: Using the Statistics module

Another option to find the median is to use the median() function from Python’s statistics module. This module comes with Python, so you don’t need to install any additional packages.

The output will be the same as in the previous step.

Full Code


Median using custom function: 4
Median using statistics module: 4


In this tutorial, we learned how to find the median of a list in Python using both a custom function and the statistics module. Finding the median is an essential step in many data analysis tasks, and Python provides an easy and efficient way to calculate it.