Median is a descriptive statistic. It is often used as a measure of the central tendency of a distribution. In this tutorial, we will look at how to get the median of values in a tuple in Python with the help of examples.

## How to calculate the median?

Median is defined as the middle value of a distribution. That is, the number of values smaller than the median is the same as the number of values larger than the median.

For example, for the numbers 1, 2, 3, 4, 5 the median value is 3 as it lies in the middle of the distribution.

From this we can see that to calculate the median, first, sort the values and then pick the middle value. If the total number of values (N) is even, then the median is the average of the (N/2)th and the (N/2 + 1)th value.

Now that we know how to compute the median mathematically, let’s see how to do it in Python.

## Median of a Tuple in Python

To get the median of a tuple in Python, you can write your own custom function or use functions defined in libraries such as `statistics`

, `numpy`

, etc.

### Median of a tuple from scratch in Python

Let’s write a function to compute the median.

def get_median(t): # sort the tuple and store the resulting list ls = sorted(t) # find the median if len(ls) % 2 != 0: # total number of values are odd # subtract 1 since indexing starts at 0 m = int((len(ls)+1)/2 - 1) return ls[m] else: m1 = int(len(ls)/2 - 1) m2 = int(len(ls)/2) return (ls[m1]+ls[m2])/2 # create a tuple t = (5, 2, 1, 3, 4) # get the median print(get_median(t))

Output:

3

Here, we use the `sorted()`

function to get a sorted copy of the tuple elements as a list. We then proceed to compute the median from this sorted list.

You can also use off-the-shelf libraries in Python to directly compute the median. These libraries have better-optimized implementations.

### Using `statistics`

library

You can use the `median()`

function from the `statistics`

standard library in Python to get the median of an iterable. Let’s look at an example.

import statistics # create a tuple t = (5, 2, 1, 3, 4) # get the median print(statistics.median(t))

Output:

3

We get the same result as above.

### Using `numpy`

library

You can also use the `numpy`

library’s `median()`

function to compute the median of a tuple. Here’s an example.

import numpy as np # create a tuple t = (5, 2, 1, 3, 4) # get the median print(np.median(t))

Output:

3.0

We get the same result we got in the above examples.

You might also be interested in –

- Python – Get median of a List
- Sort a Tuple in Python – With Examples
- Get Average of Elements in a Python Tuple

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**