# How to Find the Median of a List in Python : Various Methods

The median is a measure of central tendency. It represents the middle value of the data set. It allows you to separate the datasets into two halves. One is the upper half and the other lower half. Suppose you have a list and want to find the median of the list. Then how you can do so? In this tutorial, you will know the method to find the median of a list in Python.

## Methods to find the median of a list in Python

Let’s know all the methods that you will use to find the median.

### Method 1: Using the statistics module

In this method, you will use the statistics module. This module provides you with a median() function. You will just pass your list as an argument for the median() function.

You will get the median after running the below lines of code.

``````import statistics
sample_list = [10, 20, 30, 40, 50, 60]
median = statistics.median(sample_list )
print(median)``````

Output

`35.0`

### Method 2: Using the sorted() function

In the second method, you will first sort all the elements of a list in ascending or descending order. Then you will calculate the median. Here you have to also check whether the element is odd or not. The median of the list will depend upon it.

Run the below lines of code to find the median of a list in Python.

``````sample_list = [10, 20, 30, 40, 50, 60]
sorted_list = sorted(sample_list )
n = len(sorted_list)
if n % 2 == 0:
median = (sorted_list[n//2-1] + sorted_list[n//2])/2
else:
median = sorted_list[n//2]
print(median)
``````

Output

35.0

### Method 3: Using NumPy

The third method to find the median is the use of numpy module. It provides a mathematical function median() that will find the median of the input list. Just pass your list as an argument of the median() function.

Use the below lines of code.

``````import numpy as np
my_list = [1, 2, 3, 4, 5, 6]
median = np.median(my_list)
print(median)``````

Output

35.0

## Conclusion

If you want to normalize your dataset then mean, median e.t.c are very useful. In this tutorial, you have learned the three methods to find the median of the list. You can use any method as per convenience. But I suggest you use the NumPy package for faster and more efficient calculation.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

## SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In: 