The Wayback Machine - https://web.archive.org/web/20240913221617/https://www.geeksforgeeks.org/finding-mean-median-mode-in-python-without-libraries/
Open In App

Finding Mean, Median, Mode in Python without libraries

Last Updated : 28 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to calculate Mean, Median, and Mode with Python without using external libraries.

1. Mean: 

The mean is the average of all numbers and is sometimes called the arithmetic mean. This code calculates Mean or Average of a list containing numbers: 

We define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list.

Python3




# Python program to print
# mean of elements
 
# list of elements to calculate mean
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
 
get_sum = sum(n_num)
mean = get_sum / n
 
print("Mean / Average is: " + str(mean))


Output

Mean / Average is: 3.0

Time Complexity: O(N)
Auxiliary Space: O(1)

2. Median :

The median is the middle number in a group of numbers. This code calculates the Median of a list containing numbers

We define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function. Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out.

Python3




# Python program to print
# median of elements
 
# list of elements to calculate median
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
n_num.sort()
 
if n % 2 == 0:
    median1 = n_num[n//2]
    median2 = n_num[n//2 - 1]
    median = (median1 + median2)/2
else:
    median = n_num[n//2]
print("Median is: " + str(median))


Output

Median is: 3

Time Complexity: O(N log N)
Auxiliary Space: O(1)

3. Mode : 

The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers: 

We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list. We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.

Python3




# Python program to print
# mode of elements
from collections import Counter
 
# list of elements to calculate mode
n_num = [1, 2, 3, 4, 5, 5]
n = len(n_num)
 
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
 
if len(mode) == n:
    get_mode = "No mode found"
else:
    get_mode = "Mode is / are: " + ', '.join(map(str, mode))
     
print(get_mode)


Output

Mode is / are: 5

Time Complexity: O(n). The time complexity of this algorithm is O(n). This is because the algorithm requires looping through the entire list of elements to calculate the mode.
Auxiliary Space: O(n), The space complexity of the algorithm is O(n) as it requires the use of a dictionary to store the count for each element in the list.

Another simple approach to find mode with simple coding 

Python3




# The list for which you need to find
# the Mode
y= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8]
 
# First you sort it
# You will get numbers arranged from 3 to
# 11 in asc order
y.sort()
 
# Now open an empty list.
# What you are going to do is to count
# the occurrence of each number and append
# (or to add your findings to) L1
L1=[]
 
# You can iterate through the sorted list
# of numbers in y,
# counting the occurrence of each number,
# using the following code
 
i = 0
while i < len(y) :
    L1.append(y.count(y[i]))
    i += 1
 
# your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1],
# the occurrences for each number in sorted y
 
# now you can create a custom dictionary d1 for k : V
# where k = your values in sorted y
# and v = the occurrences of each value in y
 
# the Code is as follows
 
d1 = dict(zip(y, L1))
 
# your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}
# now what you need to do is to filter
# the k values with the highest v values.
# do this with the following code
 
d2={k for (k,v) in d1.items() if v == max(L1) }
 
print("Mode(s) is/are :" + str(d2))


Output

Mode(s) is/are :{8, 6}

Another simple approach to find mode with simple coding (HR):

Python




number_list = [1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8, 8, 8]
uniq_values = []
mode_values = []
for i in number_list:
    if i not in uniq_values:
        uniq_values.append(i)
    else:
        mode_values.append(i)
print(set(mode_values))


Output

set([8, 2, 4, 5])

Conclusion:

 We have successfully calculated mean, median, and mode of a dataset but you might be thinking ‘Will I be using these algorithms every time I want to get mean, median and mode of a dataset?’ The answer is you can but you certainly won’t. This was just to show you how the algorithm works behind the scenes when finding out any of these. For any projects, this can be achieved by simply importing an inbuilt library ‘statistics’ in Python 3, and using the inbuilt functions mean(), median() and mode(). Also, there are other external libraries that can help you achieve the same results in just 1 line of code as the code is pre-written in those libraries.



Similar Reads

Calculate Median from given values of Mean and Mode
Given two integers mean and mode, representing the Mean and Mode of a random group of data, the task is to calculate the median of that group of data. Input: mean = 3, mode = 6Output: 4 Input: mean = 1, mode = 1Output : 1 Approach: The given problem can be solved by using the mathematical relationship between mean, mode, and median of the group of
3 min read
Central Tendency in Statistics- Mean, Median, Mode
Central Tendencies are the numerical values that are used to represent a large collection of numerical data. These obtained numerical values are called central or average values. A central or average value of any statistical data or series is the variable's value representative of the entire data or its associated frequency distribution. Some commo
9 min read
How to Calculate Mean, Median and Mode in Excel
Understanding the concepts of mean, median and mode in Excel can grow your mathematics and Excel skills. Understanding how to calculate mean in Excel, work out mean on Excel, how to calculate median in Excel, find median in Excel, and calculate mode in Excel can revolutionize how you interpret data. If you're a data analyst crunching numbers for bu
9 min read
Mean, Median and Mode in R Programming
Statistical measures like mean, median, and mode are essential for summarizing and understanding the central tendency of a dataset. In R, these measures can be calculated easily using built-in functions. This article will provide a comprehensive guide on how to calculate mean, median, and mode in R Programming Language. Dataset used for Calculating
5 min read
Mean, Median and Mode
Mean, Median, and Mode are measures of the central tendency. These values are used to define the various parameters of the given data set. The measure of central tendency (Mean, Median, and Mode) gives useful insights about the data studied, these are used to study any type of data such as the average salary of employees in an organization, the med
15+ min read
Mean, Median and Mode| Comparison, Relationship and Calculation
A single value used to symbolise a whole set of data is called the Measure of Central Tendency. In comparison to other values, it is a typical value to which the majority of observations are closer. Average and Measure of Location are other names for the Measure of Central Tendency. In statistical analysis, the three principal measurements used in
7 min read
Comparison of Mean, Median and Mode| Practical Work in Geography Class 12
In this article, we will delve deep into the topic of "Comparison of Mean, Median, and Mode" from Chapter 2 of the NCERT Class 12 Practical Work Geography book. These notes are specially curated by an expert team at GeeksforGeeks for all the students. Table of Content Measures of Central TendencyComparison of Mean, Median, and ModeMeasures of Centr
4 min read
Difference Between Mean, Median, and Mode with Examples
The measures of central tendency most widely used in the field of descriptive statistics are mean, median, and mode. All the measures provide a different view of the center of the data and ensures that the information is well summarized and interpreted. The mean, or commonly known as the average value is defined as sum of all the values divided by
5 min read
Relation between Mean, Median and Mode
Relation between the Mean, Median, and Mode is the difference between the thrice of the median and twice of the mean gives Mode. Mode Mean, median, and mode are fundamental statistics measurements that give valuable insights into a given dataset. They represent the central tendency of the dataset. Although their values differ from each other for a
6 min read
Mean Median Mode Practice Questions
A collection of data's center or average is described by central tendencies. Mean, median, and mode are the most often used markers of central tendency. In this article, we will learn to solve different problems based on mean, median and mode. This article also provides solution of mean, median and mode questions along with important formulas that
8 min read
Mean, Median and Mode of Grouped Data
Suppose we want to compare the age of students in two schools and determine which school has more aged students. If we compare on the basis of individual students, we cannot conclude anything. However, if for the given data, we get a representative value that signifies the characteristics of the data, the comparison becomes easy.  A certain value r
12 min read
Find Harmonic mean using Arithmetic mean and Geometric mean
Given two numbers, first calculate arithmetic mean and geometric mean of these two numbers. Using the arithmetic mean and geometric mean so calculated, find the harmonic mean between the two numbers. Examples: Input : a = 2 b = 4 Output : 2.666 Input : a = 5 b = 15 Output : 7.500 Arithmetic Mean: Arithmetic Mean 'AM' between two numbers a and b is
5 min read
Calculate Median of elements of a Vector in R Programming - median() Function
median() function in R Language is used to calculate the median of the elements of the numeric vector passed as argument. Syntax: median(x, na.rm) Parameters: x: Numeric Vector na.rm: Boolean value to ignore NA Example 1: # R program to calculate median of a vector # Creating vector x1 &lt;- c(2, 3, 5, 7, 4, 8, 6) x2 &lt;- c(-3, -5, 6, 2, -4) # Cal
1 min read
Find Median for each Array element by excluding the index at which Median is calculated
Given an array A[] of N integers where N is even, . the task is to generate an array of medians where the median of the array is calculated by taking the median of array A[] excluding A[i]-th element. Examples: Input N = 4, A = [2, 4, 4, 3]Output: [4, 3, 3, 4]Explanation: Median after removing A[0]: New sorted array will be [3, 4, 4]. Median = 4. M
10 min read
Calculation of Median in Individual Series | Formula of Median
What is Median?When elements in the data set are organised sequentially, that is, in either an ascending or descending order of magnitude, the median can be referred to as the middle value of the data set. Its value locates in a distribution in such a way that 50% of the items are below it and 50% are above it. It focuses on the center or middle of
3 min read
Calculation of Median in Discrete Series | Formula of Median
What is Median?When elements in the data set are organised sequentially, that is, in either an ascending or descending order of magnitude, the median can be referred to as the middle value of the data set. Its value locates in a distribution in such a way that 50% of the items are below it and 50% are above it. It focuses on the center or middle of
3 min read
Calculation of Median in Continuous Series | Formula of Median
The median is a measure of central tendency that represents the middle value in a dataset, dividing it into two equal halves. In a continuous series, data is grouped into class intervals, and the median is calculated differently than in a discrete series. The median provides valuable insights into the distribution of data, especially when dealing w
6 min read
How to install Python libraries without using the pip command?
The most common practice of installing external libraries in your system is by using the Python pip command. However, there is an alternate method of manually installing Python libraries without using the pip command. In this article, we are going to discuss how to manually install a python package. Below is the Step-by-step approach to manually in
1 min read
Median and Mode using Counting Sort
Given an n sized unsorted array, find median and mode using counting sort technique. This can be useful when array elements are in limited range. Examples: Input : array a[] = {1, 1, 1, 2, 7, 1} Output : Mode = 1 Median = 1 Note: Median is average of middle two numbers (1 and 1) Input : array a[] = {9, 9, 9, 9, 9} Output : Mode = 9 Median = 9 Prere
12 min read
Difference between Register Mode and Register Indirect Mode
Prerequisite - Addressing Modes 1. Register Mode: In register addressing mode, the operand is placed in one of the 8-bit or 16-bit general-purpose registers. The data is in the register that is specified by the instruction. Example: MOV R1, R2 Instruction has register R2 and R2 has operand. 2. Register Indirect Mode: In register indirect addressing
3 min read
Coercing an Object of mode "list" to mode "call" in R Programming - as.call() Function
as.call() function in R Language is used to coerce the object of mode "list" to mode "call". The first element of the list becomes the function part of the call. Syntax: as.call(x) Parameters: x: an arbitrary R object Example 1: # R program to illustrate # as.call function # Calling the as.call() function as.call(list(list, 5, 10)) as.call(list(as.
1 min read
Difference between Relative Addressing Mode and Direct Addressing Mode
Prerequisite - Addressing Modes In an Instruction Fetch operation of the Instruction Cycle Process, addressing mode plays a crucial part. Addressing Mode is how the operand is addressed in an instruction word before being executed. 1. Relative Address Mode: In this mode, the Effective Address (EA) of the operand is calculated by adding the content
5 min read
User mode and Kernel mode Switching
In it's life span a process executes in user mode and kernel mode. The User mode is normal mode where the process has limited access. While the Kernel mode is the privileged mode where the process has unrestricted access to system resources like hardware, memory, etc. A process can access I/O Hardware registers to program it, can execute OS kernel
4 min read
Minimum mode configuration of 8086 microprocessor (Min mode)
Overview : The 8086 microprocessor operates in minimum mode when MN/MX' = 1.In minimum mode,8086 is the only processor in the system which provides all the control signals which are needed for memory operations and I/O interfacing.Here the circuit is simple but it does not support multiprocessing.The other components which are transceivers, latches
5 min read
Difference between standards mode and quirks mode
Standards mode and Quirks mode are two modes introduced by web browsers to treat new standards-compliance sites differently from old legacy sites. At present, there are three modes used by the layout engines of web browsers to work along: quirks mode, almost standards mode, and full standards mode. The document type declaration of HTML, also known
3 min read
Difference between User Mode and Privileged Mode in Cisco Router
A router is a layer 3 device used to forward packets from one network to another. It forwards the packet through one of its ports on the basis of destination IP address and the entry in the routing table. By using a routing table, it finds an optimized path between the source and destination network. In this article we will see difference between U
3 min read
Difference Between Minimum Mode and Maximum Mode in 8086 Microprocessor
Introduction : In the 8086 microprocessor, there are two modes of operation: minimum mode and maximum mode. Minimum mode is used when the 8086 microprocessor is operating as a standalone processor without any external coprocessors or support chips. In this mode, the 8086 uses a single 8-bit bus for both data and instructions, and a single 20-bit ad
3 min read
Flutter - Implement Light Mode and Dark Mode
In this article, we are working on the light theme and dark theme in the flutter application. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-content/uploads/20221205123701/lightanddarkmode-2022-12-05-12-33-32.mp4"][/video]Step By Step Implementation Step 1:
4 min read
How to Check if An App is In Dark Mode and Change it To Light Mode in Android?
In this article, we are going to first check whether the application is in Dark mode or not it the app is in Dark mode then we have to change the app to light mode. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-content/uploads/20230522220348/2023_05_22_21_5
3 min read
Sleep mode vs Hibernate mode in Computer
As we know, it is a bit difficult to shut down the computer all the time when we are on important work. It is necessary the save the work all the time if we prefer shutting down the computer. In such situations sleep mode and hibernate places a key role to return to the work which was not saved. Sleep RAM status: When the computer is turned into sl
2 min read