Python – Multimode of List
Last Updated :
09 Apr, 2023
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.
Python3
import math
from collections import Counter
test_list = [ 1 , 2 , 1 , 2 , 3 , 4 , 3 ]
print ("The original list is : " + str (test_list))
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))
print ("The multimode of list is : " + str (res))
|
Output :
The original list is : [1, 2, 1, 2, 3, 4, 3]
The multimode of list is : [1, 2, 3]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using statistics.multimode() This task can also be performed using inbuilt function of mulimode(). This is new in Python versions >= 3.8.
Python3
import statistics
test_list = [ 1 , 2 , 1 , 2 , 3 , 4 , 3 ]
print ("The original list is : " + str (test_list))
res = statistics.multimode(test_list)
print ("The multimode of list is : " + str (res))
|
Output :
The original list is : [1, 2, 1, 2, 3, 4, 3]
The multimode of list is : [1, 2, 3]
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...