Open In App

Python | Find most frequent element in a list

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, find the most frequent element in it. If there are multiple elements that appear maximum number of times, print any one of them.

Examples: 

Input : [2, 1, 2, 2, 1, 3]
Output : 2

Input : ['Dog', 'Cat', 'Dog']
Output : Dog

Approach #1 : Naive Approach
This is a brute force approach in which we make use of for loop to count the frequency of each element. If the current frequency is greater than the previous frequency, update the counter and store the element. 

Python3




# Program to find most frequent
# element in a list
 
def most_frequent(List):
    counter = 0
    num = List[0]
     
    for i in List:
        curr_frequency = List.count(i)
        if(curr_frequency> counter):
            counter = curr_frequency
            num = i
 
    return num
 
List = [2, 1, 2, 2, 1, 3]
print(most_frequent(List))


Output: 

2

 

  
Approach #2 : Pythonic Naive approach
Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we find the maximum out of it. 

Python3




# Program to find most frequent
# element in a list
def most_frequent(List):
    return max(set(List), key = List.count)
 
List = [2, 1, 2, 2, 1, 3]
print(most_frequent(List))


Output: 

2

 

  
Approach #3 : Using Counter
Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method. 

Python3




# Program to find most frequent
# element in a 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))


Output: 

2

 

Approach #4 : By finding mode 
Finding most frequent element means finding mode of the list. Hence, we use mode method from statistics.  

Python3




import statistics
from statistics import mode
 
def most_common(List):
    return(mode(List))
   
List = [2, 1, 2, 2, 1, 3]
print(most_common(List))


Output: 

2

 

Approach #5 : Using Python dictionary
Use python dictionary to save element as a key and its frequency as the value, and thus find the most frequent element.  

Python3




# Program to find most frequent
# element in a list
 
def most_frequent(List):
    dict = {}
    count, itm = 0, ''
    for item in reversed(List):
        dict[item] = dict.get(item, 0) + 1
        if dict[item] >= count :
            count, itm = dict[item], item
    return(itm)
 
List = [2, 1, 2, 2, 1, 3]
print(most_frequent(List))


Output: 

2

 

Approach #6 : Using pandas library. 
Incase of multiple values getting repeated. Print all values.

Python3




import pandas as pd
List = [2, 1, 2, 2, 1, 3, 1]
 
# Create a panda DataFrame using the list
df=pd.DataFrame({'Number': List})
 
# Creating a new dataframe to store the values
# with appropriate column name
# value_counts() returns the count based on
# the grouped column values
df1 = pd.DataFrame(data=df['Number'].value_counts(), columns=[['Number','Count']])
 
# The values in the List become the index of the new dataframe.
# Setting these index as a column
df1['Count']=df1['Number'].index
 
# Fetch the list of frequently repeated columns
list(df1[df1['Number']==df1.Number.max()]['Count'])


Output: 

[2,1]

 

Approach #7: Using numpy library

Note: Install numpy module using command “pip install numpy”

Use numpy library to create an array of unique elements and their corresponding counts. Then, find the index of the maximum count and return the corresponding element from the unique array.

Python




import numpy as np
# Program to find most frequent
# element in a list
def most_frequent(List):
    unique, counts = np.unique(List, return_counts=True)
    index = np.argmax(counts)
    return unique[index]
 
List = [2, 1, 2, 2, 1, 3]
print(most_frequent(List))


Output:

2

Time complexity: O(n) for numpy unique function and argmax
Space complexity: O(n) for storing unique values



Previous Article
Next Article

Similar Reads

Python program for most frequent word in Strings List
Given Strings List, write a Python program to get word with most number of occurrences. Example: Input : test_list = ["gfg is best for geeks", "geeks love gfg", "gfg is best"] Output : gfg Explanation : gfg occurs 3 times, most in strings in total. Input : test_list = ["geeks love gfg", "geeks are best"] Output : geeks Explanation : geeks occurs 2
6 min read
Find the k most frequent words from data set in Python
Given the data set, we can find k number of most frequent words. The solution of this problem already present as Find the k most frequent words from a file. But we can solve this problem very efficiently in Python with the help of some high performance modules. In order to do this, we'll use a high performance data type module, which is collections
2 min read
Find the most frequent value in a NumPy array
In this article, let's discuss how to find the most frequent value in the NumPy array. Steps to find the most frequency value in a NumPy array: Create a NumPy array.Apply bincount() method of NumPy to get the count of occurrences of each element in the array.The n, apply argmax() method to get the value having a maximum number of occurrences(freque
1 min read
Kth most frequent Character in a given String
Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.Examples: Input: str = "GeeksforGeeks", K = 3 Output: f Explanation: K = 3, here 'e' appears 4 times & 'g', 'k', 's' appears 2 time
6 min read
How to display most frequent value in a Pandas series?
In this article, our basic task is to print the most frequent value in a series. We can find the number of occurrences of elements using the value_counts() method. From that the most frequent element can be accessed by using the mode() method. Example 1 : # importing the module import pandas as pd # creating the series series = pd.Series(['g', 'e',
1 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collections from operator import itemgetter from itertools i
5 min read
Python Program for Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1} Output : 3 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30} Output : 10 or 20 or 30 Method 1:A simple solution is to run two
3 min read
Python | Find most common element in each column in a 2D list
Given a 2D list, write a Python program to find the most common element in each column of the 2D list. Examples: Input : [[1, 1, 3], [2, 3, 3], [3, 2, 2], [2, 1, 3]] Output : [2, 1, 3] Input : [['y', 'y'], ['y', 'x'], ['x', 'x']] Output : ['y', 'x'] Method #1 : Using most_common() from collections module most_common() return a list of the n most co
5 min read
Python | Find most common element in a 2D list
Given a 2D list (may or may not be of same length), write a Python program to find the most common element in the given 2D list. Examples: Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]] Output : 10 Input : [['geeks', 'wins'], ['techie', 'wins']] Output : wins Approach #1 : Using max() function First Pythonic approach is to use max() method of P
5 min read
Python - Least Frequent Character in String
This article gives us the methods to find the frequency of minimum occurring character in a python string. This is quite important utility nowadays and knowledge of it is always useful. Let’s discuss certain ways in which this task can be performed. Method 1 : Naive method + min() In this method, we simply iterate through the string and form a key
5 min read
three90RightbarBannerImg