Find most frequent element in a Python List
In this tutorial, we are going to see how to find the most frequent element in the Python list. The element in the list can be an integer or a string.
There are many solutions for this like:
- Using basic condition
- Using max, set and count function
- Using Counter function
- Using Mode
- And also using Python Dictionaries
Here we will show only the basic technique and also use Mode.
Basic Method
def most_frequent(my_list): counter = 0 num = my_list[0] for i in my_list: #taking each element for the list. #counting the number of occurrence of each element using the count function curr_frequency = my_list.count(i) if(curr_frequency> counter): # checking for the higest frequency. counter = curr_frequency #updating the counter. num = i #updating the highest frequency element. return num my_list = ['bba', 'aaa', 'cab', 'aba', 'dad', 'aaa'] print(most_frequent(my_list))
Output : aaa
While calling the function we can input anything, it can be an integer or a single letter or a string. It always returns the highest frequency element.
Using Mode:
import statistics from statistics import mode def most_common(my_list): return(mode(my_list)) my_list = [10, 12, 25, 25, 15, 30] print(most_common(my_list))
This is the easiest way to find the highest frequency elements.
All we have to do is import the mode function for the statistics module and perform mode operation on our list and it returns the highest frequency element.
Task:
I want you to copy the code and try out different input. Also, try to put equal frequency to both the methods to find why the first method is preferable.
Leave a Reply