#261: The Counter Class
When working with data in Python, we often need to count occurrences of items in a list or a string. While we could write our own code to do this, Python comes with the collections module that provides a convenient and efficient way to handle this task: the Counter class.
Why should we use collections.Counter?
Counter is a subclass of the dictionary. As with the regular dictionary, it can store keys and values where the keys are unique. In addition to that basic functionality, the Counter class takes on the work of splitting strings into elements, counting the unique values in a list and offers us helpful methods to get the total of all values.
This allows us to focus on the problem at hand while the nitty-gritty work of counting values gets done by the Counter.
Import collections.Counter
We do not need to install anything; all we need to do is to import Counter from the collections module:
Create a Counter
We can create a Counter object in several ways:
- From a list:
Access the tally of an element
We can access the tally of an element using the element as a key:
If the element is not present, Counter returns 0 instead of raising a KeyError:
Update the counter
We can update the counter for an element with the update method:
We can also subtract the values with the subtract method:
Yet we can also modify the tally of an element directly:
Get the most common elements
The most_common method returns a list of the n most common elements and their tallies:
Arithmetic and set operations
The Counter class supports addition, subtraction, intersection, and union operations and offers a convenient way to get the total over all elements:
Conclusion
collections.Counter is a powerful tool for counting elements in an iterable. It provides a simple and efficient way to count items, access the tallies, and perform various operations with Counter instances. Whether you are analysing text, managing inventory, or processing data, Counter can make your code cleaner and more efficient.