...

/

Counter: A High-Performance Container

Counter: A High-Performance Container

Get introduced to the Counter data-type and its functionalities.

Every language evolves by trying to cope up with the limitations hindering the way to efficiency. With every new stable version, some functionalities are deleted and added to ensure flexibility.

In this lesson, you will come across a container sequence that is still a part of Python 3: Counter (New in version 2.72.7). Let’s cover it in detail.

Counter datatype

It is a built-in class for counting objects, that implements the concept of multiset that allows elements in a set to have multiple occurrences. Like other languages have bags or multisets, Python has a Counter (an unordered) container. It’s a dict subclass for counting hashable objects. Just like a dictionary, a collection of Counter type holds elements as keys, and the number of occurrences as the value to the keys.

svg viewer

Note: The counts are allowed to be any integer value, including zero or negative counts.

The Counter() constructor either accepts an iterable like a list or a mapping like a dictionary. Run the following program to see the underlying implementation.

Press + to interact
from collections import Counter
c1 = Counter('Python 3: An In-Depth Exploration') # Using iteratable
c2 = Counter({'numbers':10, 'letters': 26}) # Using mapping
# Finding number of occurances
print(c1['o'])
print(c2['numbers'])
print(c2['alphabets'])

In the code above, you can see that we import Counter at the beginning. Now, look at line 3, we make a Counter type object c1 using an iterable (string). In the next line, we make another Counter object c2, using a dictionary (mapping).

In the second part of the program, we are finding the number of occurrences.

  • At line 7, we are finding the count of ‘o’ in c1 using subscript operator [] as: c1['o'].

  • At line 8, we are finding the count of ‘numbers’ in c2.

  • What if an element doesn’t exist? It won’t give an error and will return 0 instead. Line 9 verifies ...

Access this course and 1400+ top-rated courses and projects.