Python

Find Mean, Median, and Mode in a List in Python

The following code example shows how to Find Mean, Median, and Mode in a List in Python.

While, we find mean by summing up all elements in the list, the procedures to find median, and mode are different. In fact, the median is the middlemost element. Therefore, we need to choose the element at the middle index in the list as the median. For this purpose, we take the count of elements in the list and divide the count by zero. Further, if the count is an odd number, the resulting value when we round it off gives us the index of the median. However, the count may be an even number. In such case, we take the element at an index that we compute by dividing the count by zero. Also, we take the next element. Further, we find the average of both elements to get the median.

Likewise, we can find the mode also. For this purpose, we need to find the most frequent element. Hence, we must find the count of each element in the list. the following procedure shows how to find the mode.

At first, find the frequency of the first element and store it in a variable. After that, start a loop that scans all elements of the list starting from the second one. Whenever any element is found with a higher count, assign its value to mode.

#mean.py
#program to find mean, median, and mode in a list
import math
mylist=[7,1,2,2,3,4,7,1,9,8,12,67,23,99,5,7, 7, 6,1,22, 7,3,7,9,10,12,90, 7]

print('Original list...')
print(mylist)
mylist.sort()
print('Sorted list...')
print(mylist)

def find_MeanMedianMode():
	mylist_count=len(mylist)
	mean=0
	median=0
	mode=0
	sum=0
	for i in mylist:
		sum=sum+i
	mean=round(sum/mylist_count, 2)

	median_index=int(math.floor(mylist_count/2))
	if median_index%2==1:
		median=mylist[median_index]
	else:
		median=(mylist[median_index]+mylist[median_index+1])/2
	mode_value=mylist.count(mylist[0])
	for i in range(1, mylist_count):
		m=mylist.count(mylist[i])
		if m>=mode_value:
			mode=mylist[i]	
			mode_value=mylist.count(mylist[i])
	print('Mean: '+str(mean))
	print('Median: '+str(median))
	print('Mode: '+str(mode))

find_MeanMedianMode()

Output

A Program to Find Mean, Median, and Mode in a List in Python
A Program to Find Mean, Median, and Mode in a List in Python

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *