Python Counter Explained with Simple Examples


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Introduction to Python counter

Python counter is a subclass of ‘dict’ which keeps the count of the number of occurrences of any value. For example if we add value “this” four times in a container, it will remember that we added it four times. It can take a list, tuple, dictionary and string as an input and give us an output which will have the count of each element. In this tutorial we will cover everything about the python counter that you need to learn. We will start with constructing a counter and apply different methods over it. Moreover, we will also apply python counters on different data sets available in Python.

 

Constructing Python counter

Before constructing a python counter, we have to import the collection module as the python counter is inside this module. Once we successfully imported the module, then we are ready to go. Use import from to import counter.

# importing counter 
from collections import Counter

We can create counter instances in a number of ways. If we want to count several objects at once, we can also do that by using a sequence or iterable to initialize the counter. For example see the code below.

# importing counter 
from collections import Counter

# string as an argument
my_counter = Counter("This is bashir")

# printing
print(my_counter)

Output:

Counter({'i': 3, 's': 3, 'h': 2, ' ': 2, 'T': 1, 'b': 1, 'a': 1, 'r': 1})

In the above example, counter interates over the string and produces a dictionary with the letters as key and their frequency as values.

There are a number of other ways as well to create counter instances. See the following two different examples.

# importing counter 
from collections import Counter

# printing counter
print(Counter(b=3, c=5, d=10, g=1 ))

Output:

Counter({'d': 10, 'c': 5, 'b': 3, 'g': 1})

Here is one more example of counter instance. This time we used dict as an argument.

# importing counter 
from collections import Counter

# using dict
print(Counter({"e":3, "r":4, "p":2 }))

Output:

Counter({'r': 4, 'e': 3, 'p': 2})

 

Updating Counter Object

Python allows us to update our counter instance after initializing it. We can use update() function to update our Python counter with a new object  and counts. The update() method adds existing counts and new counts together and also creates new key count pairs if needed.

See the example below to understand the update() method.

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bashir")
print(my_counter)

# updating counter
my_counter.update("bashirbashirbashir")

# printing updated counter
print(my_counter)

Output:

Counter({'b': 1, 'a': 1, 's': 1, 'h': 1, 'i': 1, 'r': 1})
Counter({'b': 4, 'a': 4, 's': 4, 'h': 4, 'i': 4, 'r': 4})

You can see that the update method updates the existing counter and adds count to the required key. One of the advantages of update() is that it also creates a key-count pair if it couldn’t find the key in the existing counter. See the example below:

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bashir")
print(my_counter)

# updating counter
my_counter.update("bashirbashiralam")

# printing updated counter
print(my_counter)

Output:

Counter({'b': 1, 'a': 1, 's': 1, 'h': 1, 'i': 1, 'r': 1})
Counter({'a': 5, 'b': 3, 's': 3, 'h': 3, 'i': 3, 'r': 3, 'l': 1, 'm': 1})

Notice that it creates new key-count pairs when needed.

Another advantage of using update()method is that they can also take another counter as an argument and merge two counters. See the example below:

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bash")

# creating another counter
Second_counter = Counter("Hello")

# updating counter by passing counter as an argument
my_counter.update(Second_counter)

# printing updated counter
print(my_counter)

Output:

Counter({'l': 2, 'b': 1, 'a': 1, 's': 1, 'h': 1, 'H': 1, 'e': 1, 'o': 1})

 

Accessing counter's content

Python counter is similar to a python dictionary. We can perform the same actions with counters as we do with dictionaries. For example we can easily access values using the dictionary key access method. And also iterate over the keys values using the same techniques and methods.

See the example below:

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bashir alam")

# accessing counter content
print(my_counter["a"])
print(my_counter["b"])

Output:

3
1

In a similar way, we can use a for loop to loop over the key-count pair in the counter and can access them one by one. See the example below:

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bashir")

# using for loop
for i in my_counter:
   print(i, my_counter[i])

Output:

b 1
a 1
s 1
h 1
i 1
r 1

Here is one more example of using key value pairs at the same time while looping. See the example below:

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bashir")

# using for loop
for key, count in my_counter.items():
   print(key, count)

Output:

b 1
a 1
s 1
h 1
i 1
r 1

One more thing about the Python counter is that if we want to access an element or key that is not in the counter, we will get 0 instead of any error. See the example below:

# importing counter 
from collections import Counter

# create counter
my_counter = Counter("bashir")

# printing value which is not in counter
print(my_counter["z"])

Output:

0

 

Python counter with different data sets

So far we have seen strings as an argument in python counter.However, the argument is not only limited to strings only. It can take lists, tuples and dictionaries as well. In this section we will see some of those data sets as an argument to the python counter.

 

Python counter with a list

As we know a list is an iterable object that has its elements inside square brackets separated by a comma. When we use a list as an argument to the counters, then it will convert the list into keys-cout pairs, where keys will be the elements of the list and values/count will be the number of times the element occurs in the given list.

See this example, which uses list as an argument in the python counter.

# importing counter 
from collections import Counter

# create list
my_counter = ["b", "a", "s", "h", "b", "a", "a", "a"]

# printing counter
print(Counter(my_counter))

Output:

Counter({'a': 4, 'b': 2, 's': 1, 'h': 1})

Notice one thing in the output that the counter arranges the elements in an order of decreasing the count/values. It places the most repeated element in the beginning and least one at the end.

 

Python counter with a dictionary

We know that a dictionary is a sequence of key-value pairs which are written inside curly brackets. When we use a dictionary as an argument in the python counter, it will then convert it to a hashtable object where the elements will be the keys, and the values will be the count.

See the example below which uses a dictionary as an argument in the Python counter.

# importing counter 
from collections import Counter

# create dictionary
my_counter = {"b":3, "a":1, "z":10 }

# printing counter
print(Counter(my_counter))

Output:

Counter({'z': 10, 'b': 3, 'a': 1})

Notice that the counter also arranges the dictionary with placing the most counted element in the beginning and the least on at the end.

 

Python counter with a tuple

As we know tuples are a collection of objects inside round brackets separated by commas. When we use tuple as an argument in the Python counter, then it will convert the tuple into key-value pairs. Where keys will be the elements of tuple and values/count will be the number of occurrences of each element.

See the example below which uses tuple as an argument in the python counter.

# importing counter 
from collections import Counter

# create dictionary
my_counter = ("s", "s", "v", "v", "v", "v", "p")

# printing counter
print(Counter(my_counter))

Output:

Counter({'v': 4, 's': 2, 'p': 1})

Notice that the python counter also arranged the tuple in descending order based on the count value.

 

Python counter and arithmetic operations

We can perform basic arithmetic operations like addition, subtraction , union, and intersection using python counters.

See below the example of addition using python counter.

# importing counter 
from collections import Counter

# creating dic
my_dic1 =  {'x': 3, 'y': 2, 'z': -10}
my_dic2 = {'x': -12, 'y': 9, 'z':19}

#Addition using counter
my_counter = Counter(my_dic1) + Counter(my_dic2)

# printing
print(my_counter)

Output:

Counter({'y': 11, 'z': 9})

Python counter takes each key and adds their values/count and returns updated key-count pairs. Now you might notice in the above example that it didn’t return the key-count pair for element x.  Because by default python counter only returns the values which are positive. In case of x, when we add the values it gives negative value, that is why it was not returned by the python counter.

Subtraction operation is very much similar to the addition one. See the example below.

# importing counter 
from collections import Counter


# creating dic
my_dic1 =  {'x': 3, 'y': 2, 'z': -10}
my_dic2 = {'x': -12, 'y': 9, 'z':19}

#subtraction using counter
my_counter = Counter(my_dic1) - Counter(my_dic2)

# printing
print(my_counter)

Output:

Counter({'x': 15})

In a similar way we can use intersection and union as well. Intersection will give all common positive minimum values from my_dic1 and my_dic2. And union will give give positive max values from my_dict1 and my_dict2

See example below which uses intersection and union in the Python counter.

# importing counter 
from collections import Counter

# creating dic
my_dic1 =  {'x': 3, 'y': 2, 'z': -10}
my_dic2 = {'x': -12, 'y': 9, 'z':19}

#intersection in counter
print(Counter(my_dic1) & Counter(my_dic2))

# union in counter
print(Counter(my_dic1)| Counter(my_dic2))

Output:

Counter({'y': 2})
Counter({'z': 19, 'y': 9, 'x': 3})

 

Python counter with different methods

Python is known for its built-in functions and methods. There are some important methods available with python counters as well. In this section we will discuss some of the commonly used methods associated with python counters.

 

Python counter and element method

The element() method in Python counter, returns all the elements with count or value greater than zero. Elements with zero or value less than zero will not be returned. See the example below which uses element() method.

# importing counter 
from collections import Counter

# creating counter
my_counter =  Counter({'x': 3, 'y': 2, 'z': -10})

# will give you all elements with positive value and count>0
elements = my_counter.elements()
for key in elements:
   print(key)

Output:

x
x
x
y
y

Notice that element() method returns each element according to their count/value.  And didn’t return the element whose value was less than zero.

 

Python counter and most common value method

most_common() method will sort the counter as per the most common element first followed by next. It can also take a value as an argument. If we will not specify any value as an argument, then it will sort the counter and will give the most common elements from the start. The last element will be the least common element.

See the example below to understand the working of most_common() method.

# importing counter 
from collections import Counter

# creating counter
my_counter =  Counter({'x': 3, 'y': 2, 'z': -10, "h": 5, "b":1})

# most common () without argument
print(my_counter.most_common())

# with argument
print(my_counter.most_common(2))

Output:

[('h', 5), ('x', 3), ('y', 2), ('b', 1), ('z', -10)]
[('h', 5), ('x', 3)]

Notice that when we did not specify the most common value, it prints out all the elements in descending order of their occurrence including the negative counts as well. And when we specify the most common value, it prints only elements having count value equal to or greater than the specified value.

 

Python counter and clear method

clear() method is used to simply clear all of the counts from the counter object. See the example below:

# importing counter 
from collections import Counter

# creating counter
my_counter =  Counter({'x': 3, 'y': 2, 'z': -10, "h": 5, "b":1})

# clear method
print(my_counter.clear())

Output:

None

It prints None because there is nothing to print as we used clear() to clear all the counts from the object.

 

Summary

A Python counter is simply a container which holds the count of each of the elements present in the container. It takes input a list, tuple, dictionary or string which are all iterable objects and will give output that will have the count of each of the elements. In this tutorial we covered everything that you need to learn about python counters. We learned about constructing a counter and applying it on different iterable data sets. Moreover, we also covered some of the common methods that are used commonly with python counters.

 

Further Reading Section

python counter
Methods in counter
Python counter documentation

 

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

X