Python – Multimode of List

Sometimes, while working with Python lists we can have a problem in which we need to find mode in list i.e most frequently occurring character. But sometimes, we can have more than 1 modes. This situation is called multimode. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + formula
The simpler manner to approach this problem is to employ the formula for finding multimode and perform using loop shorthands. This is the most basic approach to solve this problem.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Multimode of List
# using loop + formula 
import math
from collections import Counter
  
# initialize list 
test_list = [1, 2, 1, 2, 3, 4, 3
  
# printing original list 
print("The original list is : " + str(test_list)) 
  
# Multimode of List
# using loop + formula 
res = []
test_list1 = Counter(test_list) 
temp = test_list1.most_common(1)[0][1
for ele in test_list:
  if test_list.count(ele) == temp:
    res.append(ele)
res = list(set(res))
  
# printing result 
print("The multimode of list is : " + str(res)) 

chevron_right


Output :

The original list is : [1, 2, 1, 2, 3, 4, 3]
The multimode of list is : [1, 2, 3]

 

Method #2 : Using statistics.multimode()
This task can also be performed using inbuilt function of mulimode(). This is new in Python versions >= 3.8.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Multimode of List
# using statistics.multimode() 
import statistics 
  
# initialize list 
test_list = [1, 2, 1, 2, 3, 4, 3
  
# printing original list 
print("The original list is : " + str(test_list)) 
  
# Multimode of List
# using statistics.multimode() 
res = statistics.multimode(test_list) 
  
# printing result 
print("The multimode of list is : " + str(res)) 

chevron_right


Output :

The original list is : [1, 2, 1, 2, 3, 4, 3]
The multimode of list is : [1, 2, 3]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.