How to find the median of the elements present in a list in python?

+1 vote

Best answer

You can write your own function to compute the median. But if you want to use some built-in function, you can use module Numpy or statistics. You can use Numpy with both Python2 and Python3, but statistics does not work with Python2. Here is an example:

>>> import statistics

>>> items = [1, 2, 3, 6, 8]

>>> statistics.median(items)

3

>>> vals = [11,22,12,34,21,65,34,554,23,45,12,78,65,56,78,98,765,234,10]

>>> statistics.median(vals)

45

>>> import numpy

>>> numpy.median(vals)

45.0

>>> int(numpy.median(vals))

45

>>> int(numpy.median(items))

3