How to find the median of a given list in Python

Hi everyone.

In this tutorial, we are going to learn how to find the median of a given list in Python. The median of a given set of elements is the value that separates the set in two equal parts – one part containing the elements greater than the median and the other part containing the elements lower than the median. This tutorial teaches how we can find this value from a given list of elements.

Median of a given list in Python

Suppose we have a list containing elements 2, 3, 3, 5, 6, 7, 7. The median of this set of elements is 5 which is the fourth largest and the fourth smallest number in the list. Generally, the median is the middle value of a list of elements when they are sorted. In the above example, the data is sorted. If the data is not sorted we first need to sort in order to find the median. Then we can extract the middle value. If the number of elements in the list is even then we can find the median by taking the average of two middle values in the list.

For example, for a list [3, 4, 6, 6, 7, 8, 8, 10], the median will be 6.5 (average of 6 and 7).

In python, we can find the median of a list by using the following methods.

Sorting and finding the middle value

In this method, we are going to use the sort() method to sort the elements of the list and then find the value of the middle element. See the below code to grasp it well.

def median(list):
    list.sort()
    l = len(list)
    
    mid = (l-1)//2
    
    if(l%2==0):
        return (list[mid] + list[mid+1])/2
    else:
        return list[mid]
        
list1 = [2, 3, 3, 5, 6, 7, 7]
list2 = [3, 4, 6, 6, 7, 8, 8, 10]

print("Median of list1 = ", median(list1))
print("Median of list2 = ", median(list2))

The above program gives the output as:

Median of list1 = 5
Median of list2 = 6.5

Using the statistics module

This method is pretty simple. All we need to do is import the statistics module in python and use the median() method on the given list. The code implementation for this has been given below.

import statistics


list1 = [2, 3, 3, 5, 6, 7, 7]
list2 = [3, 4, 6, 6, 7, 8, 8, 10]

print("Median of list1 = ", statistics.median(list1))
print("Median of list2 = ", statistics.median(list2))

And the output is:

Median of list1 = 5
Median of list2 = 6.5

Thank you.

Also read: Statistics Module with Examples in Python

Leave a Reply

Your email address will not be published. Required fields are marked *