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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay