Sitemap

Data Science Day 28

12 min readAug 13, 2026

--

Mean, Median and Mode

Press enter or click to view image in full size

When we work with data, one of the first questions we usually ask is:

“What does a typical value in this dataset look like?”

A dataset may contain hundreds, thousands, or even millions of observations. Looking at every individual value is rarely useful. Instead, we use a few statistical measures to summarize where the data is centred.

Three of the most common measures are the mean, median, and mode. Together, they are known as measures of central tendency.

Q: What exactly are the mean, median, and mode?

A: Mean, median, and mode describe the centre of a dataset in different ways.

  • Mean tells us the arithmetic average.
  • Median tells us the middle value after the data is arranged in order.
  • Mode tells us the value that occurs most frequently.

Although all three describe central tendency, they answer slightly different questions. Choosing the right measure depends on the type of data we have and what we are trying to understand from it.

Q: Why do we use these measures in data analysis?

A: These measures help us summarize a dataset without having to inspect every observation individually.

For example, if we are analysing employee salaries, we may calculate the mean salary to understand the overall average compensation.

If a few senior executives earn much more than everyone else, however, the mean may become misleading. In that situation, the median salary may better represent what a typical employee earns.

If we are analysing customer preferences, such as the most commonly purchased product or the most popular payment method, the mode becomes useful.

So the important question is not simply : “How do I calculate the mean, median, and mode?”

It is also : “Which measure actually represents my data properly?”

Mean

Q: What is the mean?

A: The mean, commonly called the average, is calculated by adding all the values in a dataset and dividing the result by the number of observations.

The formula is : Mean = Sum of all values / Number of values

If our observations are : x₁, x₂, x₃, …, xₙ

then : Mean = (x₁ + x₂ + x₃ + … + xₙ) / n

In statistics, we commonly use : x̄ for the sample mean

and μ for the population mean. For now, the main idea is simple:

Add all the values and divide by how many values there are.

Q: Can we calculate the mean using a simple example?

A: Consider the following dataset : 10, 30, 40, 20, 50

First, add the values : 10 + 30 + 40 + 20 + 50 = 150

There are five observations. Therefore: Mean = 150 / 5 , Mean = 30

So the mean of the dataset is 30.

Mean in Python

We can calculate the same value using basic Python:

data = [10, 30, 40, 20, 50]
mean = sum(data) / len(data)print("Mean:", mean)

Output:

Mean: 30.0

Here:

  • sum(data) adds all the values.
  • len(data) gives the number of observations.
  • Dividing the two produces the mean.

Python also provides a built-in statistics module:

import statistics
data = [10, 30, 40, 20, 50]mean = statistics.mean(data)print("Mean:", mean)

Output:

Mean: 30

Median

Q: What is the median?

A: The median represents the centre of an ordered dataset.

Before calculating the median, we must arrange the values in ascending or descending order.

If the dataset contains an odd number of observations, the median is the middle observation.

If the dataset contains an even number of observations, there is no single middle value, so we calculate the average of the two middle observations.

Q: How do we calculate the median when the number of observations is odd?

A: Consider : 30, 40, 10, 20, 50

First, sort the dataset : 10, 20, 30, 40, 50 , Here : n = 5

For an odd number of observations: Median position = (n + 1) / 2

Therefore : (5 + 1) / 2 = 3 , the third observation is 30.

So : Median = 30

Median in Python: Odd Number of Observations

We can implement the logic ourselves:

data = [30, 40, 10, 20, 50]
sorted_data = sorted(data)
n = len(sorted_data)
median = sorted_data[n // 2]print("Sorted data:", sorted_data)
print("Median:", median)

Output:

Sorted data: [10, 20, 30, 40, 50]
Median: 30

Because Python lists use zero-based indexing, n // 2 points to the middle element when the dataset contains an odd number of values.

Q: What happens if the number of observations is even?

A: Consider : 5, 6, 7, 9

There are four observations. The two middle values are: 6 and 7

Therefore : Median = (6 + 7) / 2 , Median = 6.5

Median in Python: Even Number of Observations

data = [5, 6, 7, 9]
sorted_data = sorted(data)
n = len(sorted_data)
left_middle = sorted_data[n // 2 - 1]
right_middle = sorted_data[n // 2]
median = (left_middle + right_middle) / 2print("Median:", median)

Output:

Median: 6.5

We can combine both odd and even cases into one function:

def calculate_median(data):
"""Return the median of a non-empty numerical dataset."""
    if not data:
raise ValueError("Dataset cannot be empty.")
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 1:
return sorted_data[n // 2]
left_middle = sorted_data[n // 2 - 1]
right_middle = sorted_data[n // 2]
return (left_middle + right_middle) / 2
print(calculate_median([30, 40, 10, 20, 50]))
print(calculate_median([5, 6, 7, 9]))

Output:

30
6.5

Python’s statistics module can perform the same calculation directly:

import statistics
data = [5, 6, 7, 9]print("Median:", statistics.median(data))

Output:

Median: 6.5

Mode

Q: What is the mode?

A: The mode is the value that occurs most frequently in a dataset.

Consider : 1, 2, 2, 2, 3, 3, 4, 5

The value 2 appears three times, more than any other value.

Therefore : Mode = 2

Mode in Python

A convenient way to calculate frequencies in Python is with Counter.

from collections import Counter
data = [1, 2, 2, 2, 3, 3, 4, 5]frequencies = Counter(data)mode = max(frequencies, key=frequencies.get)print("Frequencies:", frequencies)
print("Mode:", mode)

Output:

Frequencies: Counter({2: 3, 3: 2, 1: 1, 4: 1, 5: 1})
Mode: 2

This works when there is one clear mode.

However, a dataset can also have multiple modes.

Q: Can a dataset have more than one mode?

A: Yes. A dataset may have:

  • One mode — unimodal
  • Two modes — bimodal
  • Three modes — sometimes called trimodal
  • Several modes — multimodal

Consider : 1, 1, 2, 2, 3

Both 1 and 2 occur twice. Therefore : Modes = 1 and 2

Handling Multiple Modes in Python

Instead of returning only one value, we can return every value that shares the highest frequency.

from collections import Counter
data = [1, 1, 2, 2, 3]frequencies = Counter(data)highest_frequency = max(frequencies.values())modes = [
value
for value, frequency in frequencies.items()
if frequency == highest_frequency
]
print("Modes:", modes)

Output:

Modes: [1, 2]

Q: What happens when every value occurs only once?

A: Consider: 5, 6, 7, 9

Every value occurs exactly once.

For the convention used in this article, we describe this situation as having no useful mode, because no observation occurs more frequently than the others.

Therefore: Mode = No mode

This is important because the mode is not the highest value.

The value 9 is the maximum value, but it is not the mode.

Detecting No Useful Mode in Python

from collections import Counter
data = [5, 6, 7, 9]frequencies = Counter(data)highest_frequency = max(frequencies.values())if highest_frequency == 1:
print("Mode: No mode")
else:
modes = [
value
for value, frequency in frequencies.items()
if frequency == highest_frequency
]
print("Mode:", modes)

Output:

Mode: No mode

Mode and Categorical Data

One useful feature of the mode is that it can also work with categorical data.

Suppose we ask developers which programming language they prefer:

Python, Python, R, Python, SQL, R

Python occurs most frequently. Therefore: Mode = Python

We cannot calculate a meaningful arithmetic mean for values such as Python, R, and SQL, but mode works perfectly.

This makes mode particularly useful for analysing:

  • Product categories
  • Payment methods
  • Customer preferences
  • Clothing sizes
  • Browser types
  • Survey responses

Categorical Mode in Python

from collections import Counter
languages = [
"Python",
"Python",
"R",
"Python",
"SQL",
"R"
]
frequencies = Counter(languages)mode = max(frequencies, key=frequencies.get)print("Most popular language:", mode)

Output:

Most popular language: Python

Mean vs Median: Why Outliers Matter

Mean and median can sometimes produce the same result.

Consider: 10, 20, 30, 40, 50

Mean: (10 + 20 + 30 + 40 + 50) / 5 = 30

Median : 30

So: Mean = 30, Median = 30

Now imagine one observation changes dramatically: 10, 20, 30, 40, 500

The median remains: 30

But the mean becomes: (10 + 20 + 30 + 40 + 500) / 5 = 600 / 5 = 120

A single unusually large value changed the mean from 30 to 120.

The value 500 is an example of an outlier — an observation that is unusually far from most of the dataset. This demonstrates an important principle:

Get Tharun B S’s stories in your inbox

Join Medium for free to get updates from this writer.

The mean is sensitive to extreme values, while the median is much more resistant to them.

Comparing Mean and Median with Python

import statistics
data_without_outlier = [10, 20, 30, 40, 50]
data_with_outlier = [10, 20, 30, 40, 500]
print("Without outlier")
print("Mean:", statistics.mean(data_without_outlier))
print("Median:", statistics.median(data_without_outlier))
print()print("With outlier")
print("Mean:", statistics.mean(data_with_outlier))
print("Median:", statistics.median(data_with_outlier))

Output:

Without outlier
Mean: 30
Median: 30
With outlier
Mean: 120
Median: 30

The result makes the effect of the outlier immediately visible.

A Real-World Salary Example

Suppose six employees earn:

₹30,000, ₹32,000, ₹35,000, ₹38,000, ₹40,000, ₹5,00,000

The large salary at the end will pull the mean upward.

If our question is: “How much does the company pay per employee on average?”

the mean can be useful. But if our question is:

“What does a typical employee earn?”

the median may be more informative.

Salary Analysis with Python

import statistics
salaries = [
30000,
32000,
35000,
38000,
40000,
500000
]
mean_salary = statistics.mean(salaries)
median_salary = statistics.median(salaries)
print("Mean salary:", mean_salary)
print("Median salary:", median_salary)

Output:

Mean salary: 112500
Median salary: 36500.0

There is a huge difference. The mean is ₹1,12,500, largely because the ₹5,00,000 salary pulls the average upward.

The median is ₹36,500, which is much closer to the salaries earned by most employees.

Neither answer is mathematically wrong. They simply answer different questions. This is one of the most important ideas in statistics:

A calculation can be mathematically correct and still be misleading if we choose the wrong measure for the question we are trying to answer.

When Should We Use Mean, Median or Mode?

Press enter or click to view image in full size

A simple way to remember them is:

Mean → Average

Median → Middle

Mode → Most frequent

Range

Although range is not a measure of central tendency, it is often introduced alongside mean, median, and mode because it tells us something about the spread of the data.

The range is calculated as:

Range = Maximum value — Minimum value

Consider: 5, 7, 9, 6 , Maximum = 9 , Minimum = 5

Therefore: Range = 9–5 = 4

Range in Python

data = [5, 7, 9, 6]
data_range = max(data) - min(data)print("Range:", data_range)

Output:

Range: 4

Mean, median, and mode describe the centre of our data.

Range gives us a simple indication of its spread.

Case Study 1: Mean, Median, Mode and Range

Consider : 5, 7, 9, 6

Mean

Mean = (5 + 7 + 9 + 6) / 4 = 27/4 = 6.75

Median

First, sort the data: 5, 6, 7, 9

The two middle observations are: 6 and 7

Median = (6 + 7) / 2 = 6.5

Mode

Every value appears exactly once.

Mode = No mode

Range

Range = 9–5 = 4

Final results:

Mean = 6.75 , Median = 6.5 , Mode = No mode , Range = 4

Case Study 1 in Python

from collections import Counter
import statistics
data = [5, 7, 9, 6]mean = statistics.mean(data)
median = statistics.median(data)
frequencies = Counter(data)
highest_frequency = max(frequencies.values())
if highest_frequency == 1:
mode = "No mode"
else:
mode = [
value
for value, frequency in frequencies.items()
if frequency == highest_frequency
]
data_range = max(data) - min(data)print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
print("Range:", data_range)

Output:

Mean: 6.75
Median: 6.5
Mode: No mode
Range: 4

Case Study 2: A Larger Dataset

Consider : 190, 153, 168, 179, 194, 153, 165, 187, 190, 170, 165, 189, 185, 153, 147, 161, 127, 180

There are 18 observations.

Mean

The sum of the observations is : 3056

Mean = 3056 / 18 ≈ 169.78

Median

Sorted data : 127, 147, 153, 153, 153, 161, 165, 165, 168, 170, 179, 180, 185, 187, 189, 190, 190, 194

The middle observations are the 9th and 10th values : 168 and 170

Median = (168 + 170) / 2 = 169

Mode

153 occurs three times. Hence Mode = 153

Range

Range = 194–127 = 67

Final results : Mean ≈ 169.78 , Median = 169 , Mode = 153 , Range = 67

Case Study 2 in Python

import statistics
data = [
190, 153, 168, 179, 194, 153,
165, 187, 190, 170, 165, 189,
185, 153, 147, 161, 127, 180
]
mean = statistics.mean(data)
median = statistics.median(data)
mode = statistics.mode(data)
data_range = max(data) - min(data)
print("Mean:", round(mean, 2))
print("Median:", median)
print("Mode:", mode)
print("Range:", data_range)

Output:

Mean: 169.78
Median: 169.0
Mode: 153
Range: 67

Case Study 3: Finding the Median

Consider : 25, 12, 5, 24, 15, 22, 23, 25

Sorted data : 5, 12, 15, 22, 23, 24, 25, 25

There are eight observations. The middle values are : 22 and 23

Median = (22 + 23) / 2 = 22.5

Case Study 3 in Python

import statistics
data = [25, 12, 5, 24, 15, 22, 23, 25]median = statistics.median(data)print("Median:", median)

Output:

Median: 22.5

Case Study 4: Finding the Mode

Consider : 15, 42, 65, 65, 95

The number 65 occurs twice. Every other observation occurs once.

Therefore : Mode = 65

Case Study 4 in Python

import statistics
data = [15, 42, 65, 65, 95]mode = statistics.mode(data)print("Mode:", mode)

Output:

Mode: 65

Using Pandas for Mean, Median, Mode and Range

So far, we have used basic Python and the built-in statistics module.

In practical data science work, however, we often work with Pandas, especially when our data comes from CSV files, Excel files, databases, or APIs.

Consider our larger dataset again:

import pandas as pd
data = pd.Series([
190, 153, 168, 179, 194, 153,
165, 187, 190, 170, 165, 189,
185, 153, 147, 161, 127, 180
])
print("Mean:", round(data.mean(), 2))
print("Median:", data.median())
print("Mode:", data.mode().tolist())
print("Range:", data.max() - data.min())

Output:

Mean: 169.78
Median: 169.0
Mode: [153]
Range: 67

Pandas gives us convenient methods such as:

.mean()
.median()
.mode()
.min()
.max()

These methods become especially useful when working with large datasets containing many columns.

Working with a DataFrame

Real datasets normally contain several variables rather than one list of numbers.

For example:

import pandas as pd
employees = pd.DataFrame({
"Employee": [
"Asha",
"Rahul",
"Meera",
"Vikram",
"Neha"
],
"Age": [
24,
28,
31,
28,
35
],
"Salary": [
30000,
42000,
51000,
42000,
70000
]
})
print(employees)

We can analyse individual columns:

print("Average age:", employees["Age"].mean())
print("Median age:", employees["Age"].median())
print("Most common age:", employees["Age"].mode().tolist())
print()print("Average salary:", employees["Salary"].mean())
print("Median salary:", employees["Salary"].median())

This is much closer to how mean, median, and mode are used in real data analysis.

Building Our Own Statistics Function

To bring everything together, we can create one function that calculates all four measures.

from collections import Counter
def calculate_statistics(data):
"""Calculate mean, median, mode, and range."""
if not data:
raise ValueError("Dataset cannot be empty.")
sorted_data = sorted(data)
n = len(sorted_data)
# Mean
mean = sum(sorted_data) / n
# Median
if n % 2 == 1:
median = sorted_data[n // 2]
else:
left_middle = sorted_data[n // 2 - 1]
right_middle = sorted_data[n // 2]
median = (left_middle + right_middle) / 2 # Mode
frequencies = Counter(sorted_data)
highest_frequency = max(frequencies.values())
if highest_frequency == 1:
mode = "No mode"
else:
mode = [
value
for value, frequency in frequencies.items()
if frequency == highest_frequency
]
# Range
data_range = max(sorted_data) - min(sorted_data)
return {
"mean": mean,
"median": median,
"mode": mode,
"range": data_range
}
data = [
190, 153, 168, 179, 194, 153,
165, 187, 190, 170, 165, 189,
185, 153, 147, 161, 127, 180
]
results = calculate_statistics(data)print("Mean:", round(results["mean"], 2))
print("Median:", results["median"])
print("Mode:", results["mode"])
print("Range:", results["range"])

Output:

Mean: 169.78
Median: 169.0
Mode: [153]
Range: 67

Writing the function ourselves helps us understand the logic.

Using libraries such as statistics and Pandas helps us work efficiently once the underlying idea is clear.

Both are useful skills.

Final Takeaway

Mean, median, and mode may look like simple mathematical formulas, but they form the foundation of descriptive statistics.

The mean gives us the arithmetic average.

The median gives us the centre of ordered data and is especially useful when extreme values are present.

The mode tells us which observation occurs most frequently and can even be used with categorical data.

The range gives us a simple indication of how far apart the smallest and largest observations are.

Python allows us to calculate these values in several ways:

  • Basic Python helps us understand the underlying logic.
  • The statistics module gives us convenient built-in statistical functions.
  • Pandas allows us to perform the same calculations efficiently on real datasets.

But the most important lesson is not the syntax.

It is understanding which measure actually describes the data properly.

A mean can be mathematically correct and still give a poor picture of a skewed dataset.

A median may describe a typical observation better when extreme values are present.

A mode may be the only sensible measure when the data is categorical.

That is the difference between simply calculating statistics and actually analysing data.

A simple way to remember the concepts is:

Mean → Average

Median → Middle

Mode → Most frequent

Range → Maximum — Minimum

Once these ideas are clear, we are no longer just looking at a collection of numbers. We are starting to understand what the data is actually telling us.

--

--