Counters in Python

In this tutorial I am going to discuss about counters in python. We will discuss about different methods and operations which are used for manipulating counter objects.

Counters in python

Counter is a container which is included in collections module of python. It is basically a subclass of dictionary class which is used to store elements and their counts in form of a simple dictionary. It takes an iterable or mapping object as an argument and creates a dictionary which contains all unique elements from the iterable as keys and their number of occurrences throughout the iterable as their values.

Initialization

A counter object can be initialized by using the following syntax :

count_obj = collections.Counter(iterable / mapping)

We can call this method in three ways by giving three different types of arguments :

  • Using sequence of data (list, tuple or string).
  • Using a dictionary containing keys and their counts as values.
  • Using keyword argument by mapping key names to counts.

The following code shows all three types of initialization of a counter object :

import collections

# Counter object using sequence of data
count1 = collections.Counter(['a', 'g', 'c', 'a', 'b', 'h', 'g', 'a', 'd', 'e'])
print("Counter1 : ", count1)

# Counter using a dictionary
count2 = collections.Counter({'a': 4, 'b':5, 'f':1, 'd':1, 'c':2})
print("\nCounter2 : ", count2)

# Counter using keyword arguments 
count3 = collections.Counter(a=2, b=3, d=2, c=1, e=3)
print("\nCounter3 : ", count3)
Counter1 :  Counter({'a': 3, 'g': 2, 'c': 1, 'b': 1, 'h': 1, 'd': 1, 'e': 1})

Counter2 :  Counter({'b': 5, 'a': 4, 'c': 2, 'f': 1, 'd': 1})

Counter3 :  Counter({'b': 3, 'e': 3, 'a': 2, 'd': 2, 'c': 1})

Note that when a counter object is displayed it shows the elements in decreasing order of values or counts and then based on their occurrence in the iterable or mapping.

Counter object work similar to a dictionary but the only difference is that if we try to access a non-existing key:value pair then it will not throw any erro but it will give value as 0.

Methods on Counter objects

There are some special methods given for counter objects which help is easy handling and manipulating of such objects. Let's discuss some of these commonly used methods and operations.

Getting count of elements

We can access counts of any element by using the same way as we use with dictionaries to get value of a key i.e. counter_obj[key] will give us the count of 'key' element.

Let's have a look at an example :

import collections

counter1 = collections.Counter(['a', 'c', 'b', 'd', 'e', 'b', 'd', 'a', 'a', 'e'])
print("Counter : ", counter1)

print("Count of 'a' :",counter1['a'])
Counter :  Counter({'a': 3, 'b': 2, 'd': 2, 'e': 2, 'c': 1})
Count of 'a' : 3

Setting count of an element

Similar to accessing an element we can also add an element or change value of an element of a counter by using simple assignment statement. Note that a counter object unlike dictionary does not throw an error if we try to access a non-existent element but it returns its value as 0.

Let's try to add an element or update an element of a counter object in the following code :

import collections

count2 = collections.Counter({'a':3, 'b':1, 'c':2, 'd':4, 'e':3})

print("Counter object :", count2)

# Updating a value
count2['e'] = 2
print("After updating a value for an element :", count2)

# Adding an element 
count2['f'] = 4
print("After adding an element :", count2)

# Accessing a non-existent element
print("Accessing an element that does not exist in counter object : count2['g'] =", count2['g'])
Counter object : Counter({'d': 4, 'a': 3, 'e': 3, 'c': 2, 'b': 1})
After updating a value for an element : Counter({'d': 4, 'a': 3, 'c': 2, 'e': 2, 'b': 1})
After adding an element : Counter({'d': 4, 'f': 4, 'a': 3, 'c': 2, 'e': 2, 'b': 1})
Accessing an element that does not exist in counter object : count2['g'] = 0

Removing an element

We can also remove an element from a counter object using del operator given by python. Note that even if we remove an element when we try to access the counter object will not throw any error but will show its value as zero.

Let's have a look at an example :

import collections

count3 = collections.Counter({'a':2, 'b':4, 'c':1, 'd':3, 'e':2})
print("Counter object : ",count3)

#removing element 'd'
del count3['d']
print("After deleting 'd' :", count3)
print("count3['d'] = ", count3['d'])
Counter object :  Counter({'b': 4, 'd': 3, 'a': 2, 'e': 2, 'c': 1})
After deleting 'd' : Counter({'b': 4, 'a': 2, 'e': 2, 'c': 1})
count3['d'] =  0

elements( )

The elements( ) method gives us an iterator object which can be used to iterate through all the items from the counter. The order of

Let's have a look at an example :

import collections
count4 = collections.Counter({'a':2, 'b':4, 'c':1, 'd':-3, 'e':2, 'f':0})
print("Counter : ", count4)
val = count4.elements()
print("elements() return : ",val)
print("List of all values in iterator : ",list(val))
Counter :  Counter({'b': 4, 'a': 2, 'e': 2, 'c': 1, 'f': 0, 'd': -3})
elements() return :  
List of all values in iterator :  ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'e', 'e']

Note that 'd' and 'f' values are not given by the elements( ) method because they have negative and zero value respectively.

most_common( n )

The most_common( n ) method returns a list of most common elements and their counts from the counter from the most to the least common element. If n is not given as argument then it returns a list of all the elements from the highest to the lowest counts.

Let's have a look at an example :

import collections
count5 = collections.Counter({'a':1, 'b':3, 'c':0, 'd':-3, 'e':2})

#counter object
print("Counter : ", count5)

#most_common( 2 )
print("2 most common elements from the counter : ", count5.most_common(2))

#most_common( )
print("Most common elements : ", count5.most_common())
Counter :  Counter({'b': 3, 'e': 2, 'a': 1, 'c': 0, 'd': -3})
2 most common elements from the counter :  [('b', 3), ('e', 2)]
Most common elements :  [('b', 3), ('e', 2), ('a', 1), ('c', 0), ('d', -3)]

update( )

The update method is used to update one counter object by adding elements and their counts from other counter object. It adds the count for common elements of the counter otherwise adds new element in the counter using update( ) method.

Let's have a look at an example :

import collections

count1 = collections.Counter({'a':3, 'b':2, 'c':1})
count2 = collections.Counter({'a':5, 'b':1, 'c':3})

print("Counter1 : ", count1)
print("Counter2 : ", count2)
count1.update(count2)
print("AFter updating Counter 1 :", count1 )
Counter1 :  Counter({'a': 3, 'b': 2, 'c': 1})
Counter2 :  Counter({'a': 5, 'c': 3, 'b': 1})
AFter updating Counter 1 : Counter({'a': 8, 'c': 4, 'b': 3})

Arithmetic Operations

Counter objects also support some arithmetic operations like addition, subtraction, union and intersection.
The following code shows use off these operators with counter objects.

import collections

c1 = collections.Counter(a = 5, b = 2)
c2 = collections.Counter(a = 1, b = 4)

print("counter 1 :", c1)
print("counter 2 :", c2)

#Addition operation
print("\nAddition :", c1 + c2)

#Subtraction operation
print("Subtraction :", c1 - c2)

#Union operation
print("Union or Max(c1, c2) :", c1 | c2)

#Intersection operation
print("Intersection or Min(c1, c2) :", c1 & c2)
counter 1 : Counter({'a': 5, 'b': 2})
counter 2 : Counter({'b': 4, 'a': 1})

Addition : Counter({'a': 6, 'b': 6})
Subtraction : Counter({'a': 4})
Union or Max(c1, c2) : Counter({'a': 5, 'b': 4})
Intersection or Min(c1, c2) : Counter({'b': 2, 'a': 1})

Note that when we perform any operation on counter objects, a new counter object is created. And every time a new counter object is created after an operation, it discards 0 and negative count values and elements.

Let's conclude this tutorial here. In this tutorial, we have discussed about Counter objects for collections module in python. We have discussed about different methods and operations which are used for manipulating counter objects.
If you have any questions please comment below and also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment