Finding Mean, Median, Mode in Python without libraries - GeeksforGeeks (2024)

Last Updated : 28 Jan, 2024

Comments

Improve

Summarize

Suggest changes

Like Article

Like

Save

Report

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.



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } document.getElementById('article-video-tab-content').style.display = 'block'; } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); // error handling for no compatible source player.on('error', function() { var error = player.error(); console.log("Video Error: ", error); if (error && error.code === 4) { console.log("No compatible source was found for this media."); hideVideoPlayer(); } }); }, function(err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); hideVideoPlayer(); // hiding video in case of timeout (requirejs) console.log(err); }); // function to hide the video player function hideVideoPlayer() { var videoPlayer = document.getElementById('article-video'); if (videoPlayer) { videoPlayer.parentNode.removeChild(videoPlayer); } } /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content // element = document.getElementById('article-video-tab-content'); // element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Finding Mean, Median, Mode in Python without libraries - GeeksforGeeks (3)

GeeksforGeeks

Finding Mean, Median, Mode in Python without libraries - GeeksforGeeks (4)

Improve

Next Article

How To Make Histogram with Median Line using Altair in Python?

Please Login to comment...

Finding Mean, Median, Mode in Python without libraries - GeeksforGeeks (2024)

FAQs

How do you find the median in Python without a library? ›

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.

How to find mean in Python without inbuilt function? ›

To calculate the mean, find the sum of all values, and divide the sum by the number of values: Remember, we are doing this without external library… # Inside the for loop, each score from the list is added to totalScore.

How to find mode in Python without inbuilt function and dictionary? ›

However, the only way to find the mode is to line up the data (I recommended from least to greatest), and count each point and see which data point is the most common value.

How to manually calculate median in Python? ›

So in Python it goes like this:
  1. #The list of digits.
  2. nums = [1, 2, 3, 4]
  3. #Sort the list from smallest to largest.
  4. nums.sort()
  5. #Find the median.
  6. length = len(nums)
  7. if (length % 2 == 0):
  8. median = (nums[(length)//2] + nums[(length)//2-1]) / 2.
Dec 28, 2022

How do you write mean median mode in Python? ›

Mean, Median, and Mode, Now with Python..!
  1. from statistics import mean numbers = [1, 2, 3, 4, 5] print(mean(numbers))
  2. from statistics import median numbers = [1, 2, 3, 4, 5] print(median(numbers))
  3. from statistics import mode numbers = [1, 2, 3, 4, 5, 2] print(mode(numbers))
Jan 13, 2023

How to find average in Python? ›

To find the average of the numbers in a list in Python, we have multiple ways. The two main ways are using the Len() and Sum() in-built function and using the mean() function from the statistics module.

How to find mean in Python using numpy? ›

The numpy. mean() function computes the average of all the values in a numpy array. It returns a single value that represents the arithmetic mean of the input array. We can also calculate the mean across different axes such as rows or columns by specifying the axis parameter.

How to calculate median using numpy? ›

numpy. median(arr, axis=None, out=None)
  1. Purpose: Used to find the median value from 'arr' array using arithmetic median method.
  2. Parameters: arr: array_like This will be our input array to perform median method. ...
  3. Returns: median: ndarray It returns the middle value of the array.
Jan 31, 2023

What is the fastest way to find the median? ›

Finding the median

To find the median: Arrange the data points from smallest to largest. If the number of data points is odd, the median is the middle data point in the list. If the number of data points is even, the median is the average of the two middle data points in the list.

What is the easiest way to remember mean median mode and range? ›

Today, we are going to try them all together: here's a song to remind you (don't worry about the range!) “Hey diddle diddle, the median's the middle, add and divide for the mean. The mode is the one you see the most and the range is the difference between.” (Sing to the tune of “The cow jumped over the moon.”)

What is the easiest formula to find the median? ›

For a small data set, you first count the number of data points (n) and arrange the data points in increasing order. If the number of data points is uneven, you add 1 to the number of points and divide the results by 2 to get the rank of the data point whose value is the median.

How do you find the median without listing? ›

Count how many numbers are in the set. Find the pair of numbers in the middle of the figures. Find the pair's average by adding them together and dividing by two. The resulting number is the median.

How do you find the median without a data set? ›

If you know underlying distribution of the data, you can. For example, for normal distributed data, the mean and median are same (median=mode=mean). Or for exponential distribution with mean λ−1 the median is λ−1ln(2). it is impossible to obtain median without having raw data or knowing the actual data distribution.

How do you find the median without a table? ›

If the number of terms is even, the median is the mean of the two middle numbers. Arrange the numbers in order by size. If the number of terms is odd, the median is the middle term. If the number of terms is even, add the two middlemost terms and then divide by 2.

Can we find median without sorting? ›

You can certainly find the median of an array without sorting it. What is not easy is doing that efficiently. For example, you could just iterate over the elements of the array; for each element, count the number of elements less than and equal to it, until you find a value with the correct count.

Top Articles
Schielen (Fehlstellung der Augen)
Schielen (Strabismus) | Bányai Neue Augen
The Machine 2023 Showtimes Near Habersham Hills Cinemas
Laura Loomer, far-right provocateur who spread 9/11 conspiracy theory, influencing Trump as he searches for a message | CNN Politics
Thedirtyship
Academic Calendar Pbsc
How to Book Via Rail Tickets Online?
Married At First Sight Novel Serenity And Zachary Chapter 950
Hessaire Mini Split Remote Control Manual
Lord Lord You Been Blessing Me Lyrics
Promotional Code For Spades Royale
Ice Dodo Unblocked 76
Hannah Nichole Kast Twitter
How to Be an Extra in a Movie (and What to Expect)
2022 NFL Predictions
Open jazz : podcast et émission en replay | France Musique
Chi Trib Weather
Server - GIGABYTE Costa Rica
Meine Erfahrung mit Textbroker als Autor (inkl. Beispiel zu Verdienst)
Check Subdomains Of A Domain
Yonkers Garbage Schedule 2023
Greet In Cheshire Crossword Clue
8 Farmhouse Classroom Essentials
Joshua Efird Net Worth
Pwc Transparency Report
Mugshots Gaston Gazette
Https Eresponse Tarrantcounty Com
Antonio Brown Football Reference
Myrtle Beach Armslist
William Sokol National Security Advisor Resigns
Journal articles: 'State of New York and the Military Society of the War of 1812' – Grafiati
Chihuahua Adoption in Las Vegas, NV: Chihuahua Puppies for Sale in Las Vegas, NV - Adoptapet.com
Vogler Funeral Home At Forsyth Memorial Park
Rte Packaging Marugame
Waylon Jennings - Songs, Children & Death
Kagtwt
The Top 6 Most Expensive Hermès Birkin Bags
Craigslist Farm Garden Modesto
Nsfw Otp Prompt Generator Dyslexic Friendly
Metro By T Mobile Sign In
Stihl Blowers For Sale Taunton Ma
02488 - Uitvaartcentrum Texel
The Little Mermaid (2023) | Rotten Tomatoes
The Penitent One Unmasked
The Realreal Temporary Closure
Do Diversity Visa Lottery Winners Need Affidavit Of Support With Green Card Application Is Affidavit
2045 Union Ave SE, Grand Rapids, MI 49507 | Estately 🧡 | MLS# 24048395
Shaver Lake Webcam Gas Station
Sir Anthony Quayle, 76; Actor Won Distinction in Theater, Film, TV
Papitop
Jaggers Nutrition Menu
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 5972

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.