How to find the median of a list in python

Published: May 14, 2018

DMCA.com Protection Status

Solution 1: To find the median of a small python list. One can for example create a simple function:

def calculate_median(l):
    l = sorted(l)
    l_len = len(l)
    if l_len < 1:
        return None
    if l_len % 2 == 0 :
        return ( l[(l_len-1)/2] + l[(l_len+1)/2] ) / 2.0
    else:
        return l[(l_len-1)/2]

l = [1]
print( calculate_median(l) )

l = [3,1,2]
print( calculate_median(l) )

l = [1,2,3,4]
print( calculate_median(l) )

returns here:

1
2
2.5

Another example with some random numbers (between 0 and 10):

from random import randint

l = [randint(0,10) for i in range(100)]

print( calculate_median(l) )

returns for example 5.0

Solution 2: the numpy function called median

import numpy as np

l = [1]
print np.median(np.array(l))

l = [3,1,2]
print np.median(np.array(l))

l = [1,2,3,4]
print np.median(np.array(l))

Solution 3: the statistics python 3 function: statistics.median:

import statistics

l = [1, 3, 5, 7]

median(l)

returns:

 4

Note: For a list with a lot of elements see the median of medians algorithms

References