Python Counter - Python Collections Counter with Examples

Python Counter class is part of Collections module. Counter is a subclass of Dictionary and used to keep track of elements and their count.

Python Counter

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value.

Counter elements count can be positive, zero or negative integers. However there is no restriction on it’s keys and values. Although values are intended to be numbers but we can store other objects too.

Creating Python Counter Object

We can create an empty Counter or start with some initial values too.

We can also use any Iterable as argument for creating Counter object. So string literal and List can be used too for creating Counter object.

As I mentioned above, we can use non-numeric data for count values too, but that will defect the purpose of Counter class.

Python Counter Methods

Let’s look into Counter class methods and some other operations we can perform on it.

Getting Count of Elements

If we try to get the count of non-existing key, it will return 0 and not throw KeyError.

Setting Count of Elements

We can also set the count of existing element in the counter. If the element doesn’t exist, then it gets added to the counter.

Deleting an element from Counter

We can use del to delete an element from the counter object.

elements()

This method returns the list of elements in the counter. Only elements with positive counts are returned.

Above code will print “Dog” two times because it’s count is 2. Other elements will be ignored because they don’t have positive count. Counter is an unordered collection, so elements are returned in no particular order.

most_common(n)

This method returns the most common elements from the counter. If we don’t provide value of ‘n’ then sorted dictionary is returned from most common the least common elements. We can use slicing to get the least common elements on this sorted dictionary.

subtract() and update()

Counter subtract() method is used to subtract element counts from another counter. update() method is used to add counts from another counter.

Python Counter Arithmetic Operations

We can perform some arithmetic operations on Counters too, just like numbers. However only elements with positive count are returned with these operations.

Miscellaneous Operations on Python Counter

Let’s look at some code snippets for miscellaneous operations we can perform on Counter objects.

That’s all for Python Counter class.

Reference: Python Docs

By admin

Leave a Reply

%d bloggers like this: