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
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))
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.
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))
We get the same result as above.
You can also use the
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))
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.