When you work with numerical list in Python, you may need to apply aggregation like finding the average. Most common operations are built-in in Python and no extra-code is needed. That being said, there is no function or method to retrieve the median of a list, a mathematical operation that is quite common even if the concept is less known as the average.
In this tutorial, we’ll see how you can extract the median of a list.
Table of Contents
Quick reminder: what is a median?
While the average of a list is obtained by dividing the sum of the element of a list by its length, the median is somehow tricker to get. It is the middle value, which means that:
- If the list has an odd number of elements, we just have to sort it and get the element in the middle
- If the list has an even number of elements, the median is interpolated by taking the average of the two middle values
Some examples:
[1,2,3,4,5] #odd: median is 3 - position 2
[1,2,3,4,5,6] #even - median is (3+4)/2
Code language: PHP (php)
Create our own function
Using the definition we used before, we can create our own function to extract a median from a list. The code is pretty straightforward but if you want to understand it completely, keep in mind that:
- While len() count the number of elements in a list, its index starts at 0. If you have 5 elements, the median is the element whose index is 2 (and not 3).
- You need to use integer to access a value of a list by its index. Float will raise an error.
my_list = [3,4,5,1,2]
my_other_list = [3,1,6,7,4,9]
def get_median(l):
#sort list
l.sort()
#if the number of elements is even
if len(l) % 2 == 0:
#get the two middle values
value1 = l[int(len(l)/2)]
value2 = l[int(len(l)/2-1)]
#return the average
return (value1+value2)/2
#if the number of elements is odd
else:
return l[int((len(l)+1)/2 - 1)]
print(get_median(my_list))
print(get_median(my_other_list))
Code language: Python (python)
Output:
3
5.0
Code language: CSS (css)
Great, but we need to create our own function. If you don’t want to, you have an alternative solution.
Use statistics to get the median of a list
The library statistics comes with advanced functions, one of them allowing us to calculate a median.
my_list = [3,4,5,1,2]
my_other_list = [3,1,6,7,4,9]
from statistics import median
print(median(my_list))
print(median(my_other_list))
Code language: JavaScript (javascript)
Output:
3
5.0
Code language: CSS (css)