Most Frequently Occurring Items in a list in Python
In this tutorial, we will discuss sequences means we find the most occurring items in the given sequence, the sequence may be a tuple, string, list, etc. Basically this tutorial leads you towards the basic fundamentals that are used in sequences.
How to Find the Most Frequently Occurring Items in a list in Python
We have to find the most occurring element in the given sequence. This can be done by using the most_common() method that will be in the collections.Counter class. Basically this class is used to solve such type of problems. let’s say you have a list as a sequence of words that are given below :
words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ]
Now, we are using the most_common() method of the collection.Counter class to find the most common item or element as :
words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) top_three = word_counts.most_common(3) print("The top three most common items are :",top_three)
Output :
The top three most common items are : [('eyes', 8), ('the', 5), ('look', 4)]
In the above code, first, we import the counter from the collection module then pass the list through the counter method as an argument. At last, we calculate the top three most common elements from the given sequence by most_common() method.
For more information about python you can also refer the following links :
Leave a Reply