Counter class in Python
Let’s learn about Counter in Python.
Before going into details, We’ll first solve a problem with different approaches.
We want to count the number of times a number has appeared in a list. Let’s take a look at our code.
In this example, We have used a dictionary to keep track of elements, where the key is an element and the value is a count. In a loop, we are checking if the key (number) exists in the list. If yes, we are incrementing the count else we are inserting it with the initial count equal to 1. In another approach, we are using the Counter class and when initialized, we get an instance of the Counter class with a dictionary that has already calculated the frequency of elements. We can access elements in Counter, just like we do in the dictionary. Use key and we will get value.
So basically, the Counter is
Subclass of a dictionary
Collection where elements of iterable are stored as key and their count as value
An iterator is an object that can be iterated upon (In simple terms, you can run for a loop)
📝 If a key is not present in a dictionary, it will raise a KeyError. But in the case of Counter, It will just return 0 value.
If you’re interested in more Python-related content. Follow me on Twitter. DM me or Drop me a reply if you have questions or suggestions.