Efficiently Calculate Mean, Median, and Mode in Python: A Beginner’s Guide

0

Mean, Median, and Mode in Python

Mean, median, and mode are fundamental statistical measures used in almost every domain involving numerical data. 

Calculate Mean, Median, and Mode in Python
 Calculate Mean, Median, and Mode in Python

Python is an excellent programming language for performing numerical calculations. Understanding how to compute these statistics without relying on built-in libraries or modules is a valuable skill. This guide will show you how to calculate the mean, median, and mode in Python using basic programming techniques.

Mean, Median, and Mode using Python

Mean

The mean is the average value of a dataset. To calculate the mean, sum all the values and then divide by the number of values. Here’s how you can calculate the mean in Python:

# Mean
list1 = [12, 16, 20, 20, 12, 30, 25, 23, 24, 20]
mean = sum(list1) / len(list1)
print(mean)  # Output: 20.2
    

Output:

20.2
    

Median

The median is the middle value in a dataset when it is sorted in ascending order. If the number of values is even, the median is the average of the two middle numbers. Here’s how to calculate the median in Python:

# Median
list1 = [12, 16, 20, 20, 12, 30, 25, 23, 24, 20]
list1.sort()

if len(list1) % 2 == 0:
    m1 = list1[len(list1) // 2]
    m2 = list1[len(list1) // 2 - 1]
    median = (m1 + m2) / 2
else:
    median = list1[len(list1) // 2]
print(median)  # Output: 20.0
    

Output:

20.0
    

Mode

The mode is the most frequently occurring value in a dataset. Here’s how you can calculate the mode in Python:

# Mode
list1 = [12, 16, 20, 20, 12, 30, 25, 23, 24, 20]
frequency = {}

for i in list1:
    frequency.setdefault(i, 0)
    frequency[i] += 1

frequent = max(frequency.values())
for i, j in frequency.items():
    if j == frequent:
        mode = i
print(mode)  # Output: 20
    

Output:

20
    

Summary

By understanding how to calculate the mean, median, and mode in Python without using built-in libraries, you gain deeper insights into fundamental statistical concepts and improve your programming skills. 

This knowledge is essential for data analysis, scientific computing, and many other fields. Whether you are a beginner or preparing for a coding interview, mastering these techniques will enhance your problem-solving abilities.

190 Python Projects for All Levels

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
✨ Updates