w3resource logo
Python Exercises

Python Challenges: Find majority element in a list

Python Challenges - 1: Exercise-29 with Solution

Write a Python program to find majority element in a list.

Note: The majority element is the element that appears more than n/2 times where n is the number of elements in the list.


Python: Find majority element in a list

Sample Solution:-

Python Code:

def majority_element(num_list):
        idx, ctr = 0, 1
        for i in range(1, len(num_list)):
            if num_list[idx] == num_list[i]:
                ctr += 1
                ctr -= 1
                if ctr == 0:
                    idx = i
                    ctr = 1
        return num_list[idx]

print(majority_element([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6]))


Sample Output:



Python Flowchart: Find majority element in a list

Python Code Editor:

Improve this sample solution and post your code through Disqus