In this tutorial, we will learn how to find the mean, median, and mode in Python using the built-in statistics module. These statistical measures are essential for performing descriptive analysis on numerical data and provide insights into the data’s central tendency and dispersion.
Step 1: Import the Statistics Module
First, we need to import the statistics module in our Python script. This module provides various statistical functions, such as mean, median, mode, and variance.
1 |
import statistics |
Step 2: Prepare the Data Set
We will use a sample data set to demonstrate the usage of statistical functions in Python. Let’s create a list of numerical values for this purpose.
1 |
data = [10, 20, 30, 40, 50, 40, 30, 20, 10, 60] |
Step 3: Calculate the Mean
The mean is the average value of the data set. To calculate the mean, we use the mean() function from the statistics module.
1 2 |
mean_val = statistics.mean(data) print("Mean of the data set: ", mean_val) |
Step 4: Calculate the Median
The median is the middle value of the data set when sorted in ascending or descending order. To calculate the median, we use the median() function from the statistics module.
1 2 |
median_val = statistics.median(data) print("Median of the data set: ", median_val) |
Step 5: Calculate the Mode
The mode is the most frequent value or value in the data set. To calculate the mode, we use the mode() function from the statistics module. If there is more than one mode in the data set, the function will return only the first mode it encounters.
1 2 |
mode_val = statistics.mode(data) print("Mode of the data set: ", mode_val) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 |
import statistics data = [10, 20, 30, 40, 50, 40, 30, 20, 10, 60] mean_val = statistics.mean(data) print("Mean of the data set: ", mean_val) median_val = statistics.median(data) print("Median of the data set: ", median_val) mode_val = statistics.mode(data) print("Mode of the data set: ", mode_val) |
Output
Mean of the data set: 32 Median of the data set: 30 Mode of the data set: 10
Conclusion
In this tutorial, we learned how to find the mean, median, and mode in Python using the built-in statistics module. This module helps us perform various descriptive statistical analysis on numerical data, which is essential for understanding and interpreting the data effectively.