Skip to main content
python-median-example

Python Median Method Example

In this tutorial, I will discuss the python median() method with examples and uses. The python median method help to calculate the median value from an unsorted data list.

Python 3.4 introduced a statistics package that has median() method. The median function is used to calculate the median of data.

The most significant advantage of using the median() method is that the data-list does not need to be sorted before being sent as a parameter to the median() function.

This method is used in the statistical calculation of data. The static formula to calculate the median is –

Median = {(n + 1) / 2}th Value

The statistics median is the help to find out the central location of the data sequence, list or any iterator. Its returns the median (middle value) of numeric data.

If the number of data points is odd, return the middle data point.

If the list contains an even number of elements, the function should return the average of the middle two.

How To Find Dataset Median in Python

The dataset list can be of any size and the number could be in any order. Let’s take a simple example on a list and find the median using the python mediun() method-

#test.py
import statistics
list_data = [12, 32, 44, 11, 5]
print(statistics.median(list_data))

if you run the above code, You will see that 12 is the median number.

Now, let’s find a median where the list contains an even number of items.

#test.py
import statistics
list_data = [12, 32, 44, 11, 5, 47]
print(statistics.median(list_data))

The above code will return 22.0 as the median value of the passed list.

Error – median() method

The median() method send error if the items are empty or null, then StatisticsError is raised.

median of a tuple in Python

we can also median of tuple data set. Let’s have a below example –

//test.py
import statistics
list_data = (12, 22, 15, 66, 35, 47)
print(statistics.median(list_data))

The above code will return a 28.5 value as a median of the above tuple.

Leave a Reply

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