Search code examples
pythonlistfrequency

How to find most frequent element in a list with python


I want to find most frequent element in a list, but my code is not working. What should I do? I'm getting

**IndentationError: unexpected indent Error

My code

A = [7, 9, 2, 7, 8, 3, 5, 7, 11, 3, 7]  
def mstfrqent(A): 
counter = 0
num = A[0] 
for i in A: 
    curr_frequency = A.count(i) 
return i
print(mstfrqent(A))

Solution

  • You should use another for loop.

    Btw you should give more understandable list names, it will be more efficent for work.

    A = [7, 9, 2, 7, 8, 3, 5, 7, 11, 3, 7] 
    
    def mstfrqent(A): 
        counter = 0
        num = A[0] 
    
        for i in A: 
            curr_frequency = A.count(i) 
            if(curr_frequency> counter): 
                counter = curr_frequency 
                num = i 
    
        return num 
    
    print(mstfrqent(A))