median Function of statistics Module in Python (Example)
In this article, I’ll illustrate how to apply the statistics.median function in Python programming.
Table of contents:
Let’s do this…
The first step is to create some example data:
my_list = [4, 3, 8, 2, 7, 3, 8, 4, 7, 1, 5] # Create example list print(my_list) # Print example list # [4, 3, 8, 2, 7, 3, 8, 4, 7, 1, 5]
The previous output of the Python console visualizes the structure of our example data – We have created a list object containing 11 integer values.
Example: Get Median Using median() Function of statistics Module
We first have to load the statistics module:
import statistics # Import statistics
Next, we can apply the statistics.median function to return the median of our list:
print(statistics.median(my_list)) # Apply median() function # 4
As you can see, the median of our list is equal to 4.
Note that we have calculated the middle value of a data set using the standard median function of the statistics module.
However, the statistics module also provides alternative mode functions such as median_low() to get the low median, median_high() to find the high median, and median_grouped() to compute the 50th percentile of grouped data. More info can be found here.
Video & Further Resources
Have a look at the following video on my YouTube channel. In the video, I show how to get the middle value of data using the Python codes of this tutorial:
In addition, you might read the related tutorials on statisticsglobe.com. You can find some tutorials below:
- Calculate Median in Python
- Calculate Median by Group in Python
- Median of Array with np.median Function of NumPy Library
- mean() Function of statistics Module
- Mode of NumPy Array in Python
- Python Programming Overview
This tutorial has shown how to apply the statistics.median function to calculate the median of a list in Python programming. If you have any additional comments and/or questions, please let me know in the comments section.