Python | Find the most frequent item in a list

Examples :

  Input:  [2, 1, 2, 2, 1, 3]  Output:  2  Input:  [`Dog`,` Cat`, `Dog`]  Output:  Dog 

Approach # 1: Naive Appraoh

This is a brute force method in which we use a for loop to count the frequency of each element. If the current frequency is greater than the previous frequency, update the counter and save the element.

# Program for finding the most frequent
# item in list

  

def most_frequent ( List ):

counter = 0

num = List [ 0 ]

 

for i in List :

curr_frequency = List . count (i)

if (curr_frequency & gt; counter):

counter = curr_frequency

num = i

 

return num

 

List = [ 2 , 1 , 2 , 2 , 1 , 3 ]

print (most_frequent ( List ))

Exit:

 2 

Approach # 2. Pythonic Naive Appraoch

Create a set from the list so that duplicate elements are removed. Then find the largest number of occurrences of each element in the set, and that way we will find the most of it.

# Program for finding the most frequent
# item in the list

def most_frequent ( List ):

return max ( set ( List ), key = List . count)

 

List = [ 2 , 1 , 2 , 2 , 1 , 3 ]

print (most_frequent ( List ))

Exit :

 2 

Approach # 3 Using counter

Use a Python counter that returns the count of each item in a list. This way we simply find the most common element using most_common () .

# Program for finding the most frequent
# item in the list

 

from collections import Counter

 

def most_frequent ( List ):

occurence_count = Counter ( List )

return occurence_count.most_common ( 1 ) [ 0 ] [ 0 ]

  

List = [ 2 , 1 , 2 , 2 , 1 , 3 ]

print (most_frequent ( List ))

Exit :

 2 

Approach # 4: by finding the mode

Finding the most frequent item means the search mode in the list. Therefore, we are using the mode method from statistics.

import statistics

from statistics import mode

 

def most_common ( List ):

  return (mode ( List ))

 

List = [ 2 , 1 , 2 , 2 , 1 , 3 ]

print (most_common ( List ))

Exit :

 2 

Approach # 5 Using a Python Dictionary

Use a Python Dictionary to store an element as a key and its frequency as a value and thus find the most frequent element.

# Program for finding the most frequent
# item in the list

 

def most_frequent ( List ):

dict = {}

count, itm = 0 , ``

for item in reversed ( List ):

dict [item] = dict . get (item, 0 ) + 1

if dict [item] & gt; = count:

  count, itm = dict [item], item

  return (itm)

  

List = [ 2 , 1 , 2 , 2 , 1 , 3 ]

print (most_frequent ( List ))

Exit :

 2