Find the most frequent value in a list in Python

In Python lists data structures there are many approaches to find the frequently occurring value present in the list, We will discuss some approaches here.

Approaches with examples

  1. Using for loop :
    This is a bit confusing approach rather a  brutal one but familiar for python beginners, we will be using for loop here to count the frequencies of the elements/values in the list and apply the if statement and keep updating the counter. It is a common method but not so efficient as the code gets very larger

    list_no1 = [2,3,2,4,4,4,6,6,8,8,7,0,7,7,2,3,2,2,1,1,0]
    #creating an function 
    def frequent(list_no1):
        count = 0
        no = list_no1[0]
        #for loop 
        for i in  list_no1:
            current_freq = list_no1.count(i)
            if (current_freq > count):
                count = current_freq
                num = i
        return num 
    Output: 2

    So the most frequent value in our list is 2 and we are able to find it in Python.

  2. By finding mode :
    The mode is nothing but mos frequently occurring number in a list it is an important part of statistics, Python allows us to import statistics module and perform statistical operations. This is one of the efficient approaches of finding the most frequent value in Python, let’s see the code:

    #importing libraries 
    import statistics 
    from statistics import mode 
    list_no1 = [2,3,2,4,4,4,6,6,8,8,7,0,7,7,2,3,2,2,1,1,0]
    frequent = mode(list_no1)
    Output: 2

Using max & set functions :
In this approach, we will be creating a set of the list for deleting the duplicate values  and then make use of a max function which takes in two arguments an iterable & a key function which will return mostly occurred value

list_no1 = [2,3,2,4,4,4,6,6,8,8,7,0,7,7,2,3,2,2,1,1,0]
frequent = max(set(list_no1), key = list_no1.count)
Output: 2

These were some easy approaches to find the most frequent value in a list with Python programming.
So we can see that the output for every approach is the same for the same list_no1.
I hope this would help.
Thank you!

Also read :
Python isinstance() function with example

Leave a Reply

Your email address will not be published. Required fields are marked *