Counter in Python-What is Counter & how to use it?

Chinmai Rane
GDSC UMIT
Published in
4 min readMay 1, 2022

When tackling any task that requires counting the elements of a container object. For example, you could want to count the number of times a word appears in a text, or you might want to know the most often used number in a list object. In such instances, Python’s collections module has a useful utility called Counter, which is a built-in class ().

In this blog, I will define Counter() and help you understand how it can make counting easier in python.

What is Counter in Python?

According to docs.python.org ,

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

In other words, the counter counts the elements supplied in and returns a key-value pair with the element count. It keeps track of how frequently each element in the container appears. It accepts an iterable object as an input and returns a dictionary. In this dictionary,

a key is defined as an element in an iterable, and values an element’s frequency in an iterable.

In Python, a counter counts hashable objects (those with a hash value that does not change throughout the course of their lifespan).Counter returns sorted objects sorted after processing. This is due to heap sort used in the source code for Counter.

How to use Counter() ?

To use Counter, you must first import it from the collections module. Because Python is case sensitive, the capital “C” in Counter is required for import. In counter, objects may be defined in a variety of ways:

1)Using List:

2)Using String:

3)Using Tuple:

4)Using Dictionary:

There are different ways with which we can access the counts from Counter too. One method has been shown above while defining objects. Others are mentioned below,

1)Printing both key and value:

2)Printing only keys:

3)Printing only values:

Now that we have seen how to access and define elements and objects we will see the methods in Counter class.

1)most_common([n]) -

This method can be used to find the most common elements in a collection object.

2)elements()-

This method will return you all the elements with count >0.

3)update() -

This method is used to update the elements from another Counter.

4)subtract() -

This method is used to subtract the elements from another Counter.

Conclusion:

In this blog, I have explained how to use the Python Counter() class to count things in an iterable. We have also seen that counts are always displayed in descending order.

I hope you found this blog to be informative.

Thank you for taking the time to read this!

--

--