Counter (collections) in Python

Pranay Gore
2 min readMar 21, 2019

A Counter is a subclass of dict. It is an unordered collection container in python which stores items keys and it’s count as values in a dictionary object.

It keeps the track of values if added multiple times. We can create an empty counter container by,

c=Counter()

There are different ways we can initialize Counter.

By sequence of items.

By keys and counts in a dictionary.

Using name:value mapping.

We have many ways by which we can access counts from Counter object.

Counter does not raise any exception for unknown or non-existent key. If key is not present, ‘0’ is returned as it’s value.

Update() method is used to update the Counter object.

There are few more methods used to get some insights from Counter object.

  1. elements() : This method produces all of the items in the Counter sorted by the number of occurrences of the item.
  2. most_common() : Returns a sequence of the n most frequently encountered input values.

We can use these functions as:

We can also perform couple of arithmetic and set operations on Counter object in Python. Some examples are as below:

I hope you have learnt many things about Counter object and various operations on it.

Above shown code can be accessed from :collections-in-python/counter.ipynb

Thanks for reading. cheers :-)

--

--

Pranay Gore

Learner | Big data & Cloud evangelist | Python developer | Amuser & Original