How to Determine the Most Frequently Occurring items in a List in Python



Python


In this article, we show how to determine the most frequently occurring items in a list in Python.

Let's say we have a list composed of various items.

Using the Counter() function in the collections class, we can count all of the words in a list. We can then use the most_common() function to find the most frequently occurring items in a list.

The most_common() function takes in 1 parameter, the top most common occurring items in the list. If 1 is specified, thi would return the most common or frequently occurring item in the list. If 2 is specified, this returns the 2 most frequent items in the list. If 3 is specified, this returns the 3 most frequent items in the list. And so on.

The function returns the top items with the number of how many times they appear.

Below is the code on how this is done.



So the first thing we have to do is import Counter from the collections class.

We then have a list, called words, which stores the names of various insects.

We then create a variable, word_counts, which counts all the words in the list (along with the number of times each word occurs).

We next create a variable, topword, which stores the most frequently occurring word in the list. We specify the number 1 to return the number 1 top occurring word in the list.

We next create another variable, top2words, which stores the 2 most frequently occurring words in the list. We specify the number 2 to return the number 2 top occurring words in the list.

We next create another variable, top3words, which stores the 3 most frequently occurring words in the list. We specify the number 3 to return the number 3 top occurring words in the list. Note that 'bee', 'caterpillar', and 'ant' all occur 1 time. In this case, the function will simply return the word that occurs first (from left to right).

So this is how to determine the most frequently occurring items in a list in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...