Member-only story
A note on Python Collections.Counter
One of the most useful features of Python is its built-in data structures. One such data structure is the collections.Counter module, which is used to count the occurrences of elements in a sequence.
The collections.Counter is a subclass of the dictionary object, which takes an iterable as an argument and returns a dictionary where the keys are the elements of the iterable, and the values are the count of occurrences of that element in the iterable.
Let’s take an example to understand how the collections.Counter module works:
from collections import Counter
fruits = ['apple', 'banana', 'cherry', 'apple', 'cherry', 'cherry']
fruit_count = Counter(fruits)
print(fruit_count)
# Output
Counter({'cherry': 3, 'apple': 2, 'banana': 1})
In the above example, we created a list of fruits and passed it to the Counter module. The Counter module then returned a dictionary-like object where the keys are the fruits, and the values are the count of each fruit in the list.
We can also create a Counter object from a string, where the Counter object will count the frequency of each character in the string.
string = "Python is a powerful programming language"
char_count = Counter(string)
print(char_count)
The collections.Counter module provides various methods to perform operations on the Counter object, such as finding the most common elements, subtracting or adding elements, and many more.