Find Most Frequently Occurring Item in a List in Python

Spread the love

Problem –

You have a list or a sequence of items and you want to find the most frequently occurring item from that list or the sequence.

Solution –

Let’s say we have some list of words and you want to find out which words occurs most often in this list.


In [1]: words = ["I","can't","get","you","out","of","me","without","this",
   ...:         "without","you","I","don't","feel","anything","at","all",
   ...:       "I","can't","feel","without","you","I","can't","feel","anything",
   ...:         "at","all","anything","at","all"]

To do that we can use the collection.Counter class in python.

In [2]: from collections import Counter

In [3]: word_counts = Counter(words)

In [4]: top_three = word_counts.most_common(3)

In [5]: top_three
Out[5]: [('I', 4), ("can't", 3), ('you', 3)]

Under the hood, a counter is dictionary that counts the occurrences of items.

In [6]: word_counts["anything"]
Out[6]: 3

In [7]: word_counts["without"]
Out[7]: 3

This also has update method to add more counts of words.

In [9]: word_counts.update(more_words)

In [10]: top_three = word_counts.most_common(3)

In [11]: top_three
Out[11]: [('I', 8), ("can't", 5), ('you', 5)]

With Counters, you can also do various mathematical operations like combine or subtract word counts.


In [12]: a = Counter(words)

In [13]: b = Counter(more_words)

In [14]: a + b 
Out[14]: 
Counter({'I': 8,
         "can't": 5,
         'get': 3,
         'you': 5,
         'out': 3,
         'of': 3,
         'me': 3,
         'without': 3,
         'this': 1,
         "don't": 1,
         'feel': 3,
         'anything': 3,
         'at': 3,
         'all': 3,
         'know': 2,
         "It's": 1,
         'better': 2,
         "you're": 1})

In [15]: a - b 
Out[15]: 
Counter({"can't": 1,
         'you': 1,
         'without': 3,
         'this': 1,
         "don't": 1,
         'feel': 3,
         'anything': 3,
         'at': 3,
         'all': 3})

In [16]: 

Rating: 1 out of 5.

Leave a Reply