DEV Community

Hamdy Abou El Anein
Hamdy Abou El Anein

Posted on

How to find the N most present element in a list in Python πŸ’» 🐍

If you have a list in Python 🐍 and you need to find for example the 3 elements that are the must present in the list.

You can do it like this :

Create a list

mylist = [1,2,3,4,4,4,4,5,5,6,7,8,8,8,9]
Enter fullscreen mode Exit fullscreen mode

Create two variables, maxcount is the number N of elements that we are searching.

count = 1
maxcount = 3

Enter fullscreen mode Exit fullscreen mode

Use a while loop to find what we are looking for :

while count <= maxcount:
    num = max(set(mylist), key=mylist.count)
    print(num)
    count+=1
    while num in mylist:
        mylist.remove(num) #Here we remove the element that was the max
Enter fullscreen mode Exit fullscreen mode

Now the full code:

mylist = [1,2,3,4,4,4,4,5,5,6,7,8,8,8,9]

count = 1
maxcount = 3

while count <= maxcount:
    num = max(set(mylist), key=mylist.count)
    print(num)
    count+=1
    while num in mylist:
        mylist.remove(num)

Enter fullscreen mode Exit fullscreen mode

Now the result is :

4
8
5
Enter fullscreen mode Exit fullscreen mode

You can even add them to a new list...

Image description

Top comments (0)