# Median Calculation Using Python

## Median value of a Distribution:

Median is the middle value of the data in a distribution - provided the data is sorted in ascending or descending order.

When the data has odd number of items, the median is calculated by the value at (n+1)/2 position.

When the data has even number of items, the median is calculated by taking mean of the values at n/2 position and (n+2)/2 position.

While extreme values or outliers present in the distribution affect the mean those outliers do not affect the median.

median(data)

## Method Overview:

The python function median() returns the middle of a distribution passed by the parameter "data", which is a sequence or of type any other iterator.

## Exceptions:

If the data passed is empty Python raises a StatisticsError.

## Example Python program to calculate the Median of a distribution:

 #import the python statistics module import statistics   # Distribution with odd number of items dataPoints1 = [12, 25, 37, 50, 62]   # Distribution with even number of items dataPoints2 = [12, 25, 37, 50]   # Calculate median for the distribution with odd number of items median1 = statistics.median(dataPoints1)   # Find median value of the distribution with even number of items median2 = statistics.median(dataPoints2);   print("Median Value1:{}".format(median1)) print("Median Value2:{}".format(median2))

## Output of sample Python program that calculates the Median of a distribution:

 Median Value1:37 Median Value2:31.0