Python Counter in Collections with Example

What is Python Counter?

Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class.

The counter is a sub-class available inside the dictionary class. Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.

Why use Python Counter?

Here, are major reasons for using Python 3 Counter:

  • The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.
  • It allows you to count the items in an iterable list.
  • Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.
  • A Counter can also count elements from another counter

In this Python tutorial you will learn:

Introduction to Python Counter

Python Counter takes in input a list, tuple, dictionary, string, which are all iterable objects, and it will give you output that will have the count of each element.

Counter with String

In Python, everything is an object and string is an object too. Python string can be created simply by enclosing characters in the double quote. Python does not support a character type. These are treated as strings of length one, also considered as a substring.

In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.


Arithmetic operation on Python Counter

Arithmetic operation like addition, subtraction, intersection and union can be done on a Counter as shown in the example below: