Counter class in Python

Rohit Patil
2 min readJan 8, 2022

--

Let’s learn about Counter in Python.

Before going in details, We’ll first solve a problem with different approaches.

We want to count 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 key is an element and value is count. In loop, we are checking if key (number) is existing in list. If yes, we are incrementing count else we are inserting with initial count is equal to 1. In other approach, we are using Counter class and when initialised, we are getting an instance of Counter class with a dictionary which has already calculated frequency of elements. We can access elements in Counter, just like we do in dictionary. Use key and we will get value.

So basically, Counter is

  • Subclass of a dictionary
  • Collection where element of iterable are stored as key and their count as value

An iterator is an object that can be iterated upon (In simple term, you can run for loop)

📝 If a key is not present in a dictionary, it will raise KeyError. But in case of Counter, It will just return 0 value.

If you’re interested in more Python related contents. Follow me on twitter. DM me or Drop a reply if you have questions or suggestions.

--

--

Rohit Patil

👨‍💻 Former Tech Lead, Software Consultant & Backend Engineer with 4+ years of hands-on expertise 🚀