What is counters in Python?

Counter is a container included in the collections module. Now you all must be wondering what is a container. Don’t worry first let’s discuss about the container.

What is Container?

Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built in containers are Tuple, list, and dictionary. Others are included in Collections module.

A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as a dictionary. This is equivalent to a bag or multiset of other languages.

In Python, counters are objects that are used to count occurrences of elements in a list or an iterable. They are implemented using a dictionary, where the keys are the elements of the iterable, and the values are the counts of occurrences of those elements.

Counters are useful in situations where we need to count the frequency of occurrences of elements in a collection. For example, we might want to count the number of times each word appears in a text document or the number of occurrences of each letter in a string.

Python provides the Counter class in the collections module to create counters. The Counter class provides various methods to manipulate and access the counts of elements in the counter. Some of the commonly used methods are:

  • most_common([n]): Returns a list of the n most common elements and their counts, in descending order.
  • update(iterable): Updates the counter with the counts of elements in the iterable.
  • elements(): Returns an iterator over the elements of the counter, repeated as many times as their count.

Here is an example usage of the Counter class: 

 

from collections import Counter

lst = ['apple', 'orange', 'banana', 'apple', 'orange', 'orange']
counter = Counter(lst)
print(counter) # Counter({'orange': 3, 'apple': 2, 'banana': 1})

In this example, we create a Counter object from a list, and it counts the number of occurrences of each element in the list. We can see the counts by printing the Counter object.

Submit Your Programming Assignment Details