Method # 1: The Naive Method
As a brute force method, we simply count all the elements and then just return the number of elements that remains at the maximum at the end. This is the main technique one might think of doing when faced with this problem.
# Python3 demo code # to get the most frequent element # using the naive method # initializing list test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , < / code> 5 , 4 ] # print original list print ( "Original list:" + str (test_list)) # using a naive method for # get the most frequent element max = 0 res = test_list [ 0 ] for i in test_list: freq = test_list.count (i) if freq" max : max = freq res = i # print result print ( " Most frequent number is: " + str (res)) |
Output:
Original list: [9, 4, 5, 4, 4, 5, 9, 5 , 4] Most frequent number is: 4
Method # 2: Using max () + set ()
Conversion list to set and maximize function in relation to The number of each number in the list makes this task easy and is the most elegant way to accomplish this.
# Python3 demo code # to get the most frequent element # using max () + set () # initializing list test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , 5 , 4 ] # print original list print ( "Original list:" + str (test_list)) # using max () + set () to # get the most frequent element res = max ( set (test_list), key = test_list.count) # print result print ( "Most frequent number is:" + str (res)) |
Output:
Original list: [9, 4, 5, 4, 4, 5, 9, 5, 4] Most frequent number is: 4
Method # 3: Using statistics.mode()
Mode is denoted as an element of maximum frequency in mathematics, and python allocates integer library for the aggregate function, and this can also be used to solve this problem.
# Python3 demo code # to get the most frequent item # using statistics.mode () import statistics # initializing list test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , 5 , 4 ] # print original list pr int ( "Original list:" + str (test_list)) # using statistics.mode () for # get the most frequent element res = statistics.mode (test_list) # print result print ( "Most frequent number is:" + str (res)) |
Output:
Original list: [9, 4, 5, 4, 4, 5, 9, 5, 4] Most frequent number is: 4
Method # 4: Using collections.Counter.most_common()
A lesser known method to accomplish this particular task, Counter ()
uses the most_common function to accomplish this in one line. This is an innovative and different way to achieve this.
# Python3 demo code # to get most common element # using collection.Counter.most_common () from collections import Counter # initializing list test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , 5 , 4 ] # print original list print ( "Original list:" + str (test_list)) # using most_common for # get the most frequent element test_list = Counter (test_list) res = test_list.most _common ( 1 ) [ 0 ] [ 0 ] # print result print ( " Most frequent number is: " + str (res)) |
Output:
Original list: [9, 4, 5, 4, 4, 5, 9, 5, 4] Most frequent number is: 4