It’s all about Python Counter

It’s all about Python Counter

4 mins read282 Views Comment
Updated on Feb 9, 2023 16:48 IST

In this article you will learn about Python Counter. You will get to know how to access and update Object Counts in Python  with programming examples.

2023_02_MicrosoftTeams-image-1.jpg

Python’s Counter class is a useful and convenient way to count occurrences of items in a list or other iterable. Its methods and operators make it easy to work with the counts of items and compare them. 

Today, we will discuss Python Counter and learn how to work with it using example codes. So, without further ado, let’s get started. 

We will be covering the following sections: 

Counting Objects in Python 

To determine the frequency of objects in a given data source, you need to count the number of times they appear. This can be simple when the list is short but more difficult when it is long. A counter, an integer variable with an initial value of zero, is often used to count the number of objects. When counting the occurrences of one object, only one Counter is needed, but multiple counters must be created for multiple objects. A Python dictionary can also be used to count several different objects at once. The keys of the dictionary will store the objects being counted, and the values will hold the number of repetitions of each object. 

For example, the following program counts the number of letters in the word “occurrences”: 


 
# Initialize an empty dictionary to store the letter count
letter_count = {}
# Iterate through each letter in the word
for letter in "occurrences":
# If the letter is already in the dictionary, increment its count
if letter in letter_count:
letter_count[letter] += 1
# If the letter is not in the dictionary, add it and set its count to 1
else:
letter_count[letter] = 1
# Print the final letter count
print(letter_count)
Copy code

Output: 

2023_02_1.jpg

Explanation: 

The for loop iterates over the letters in the word “occurrences.” In each iteration, the conditional statement checks if the letter is in the dictionary. If it is, its count is incremented. If the letter is not in the dictionary, a new key is created with it, and its count is set to 1. When you access the dictionary, you see that the letters work as keys and the values as counts. 

Leap Year Programs in C 
How to Use Python Print Function
How to use Python Arithmetic Operators
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Introduction to Python Counter 

Python’s collections module provides a Counter class that is a convenient way to count occurrences of items in a list or other iterable. A Counter object is a dictionary-like object that maps items to their counts. 

Creating a Counter is simple. You can create an empty counter by calling the Counter constructor with no arguments, or you can create a counter from an iterable by passing the iterable as an argument to the constructor.  

Here’s an example of how to use the Counter class to count the number of letters in the word “occurrences”: 


 
from collections import Counter
# Initialize a Counter object with the word "occurrences"
letter_count = Counter("occurrences")
# Print the final letter count
print(letter_count)
Copy code

Output: 

2023_02_2.jpg

You can also use the most_common() method to return a list of the n most common elements and their counts from the most common to the least: 


 
letter_count.most_common()
Copy code

Updating Object Counts in Python 

Once you have created a Counter object, you can use the .update() method to add new objects and their counts. Unlike the update() method for dictionaries, the .update() method for Counter objects adds the counts together rather than replacing them. It also creates new key-value pairs when necessary.  

The .update() method can be used with both iterable (such as lists or strings) and mappings of counts (such as dictionaries). When an iterable is used as an argument, the method will count the items in the iterable and update the Counter accordingly. 

Look at the example below (continuation of the previous example): 


 
letter_count.update("concurrent")
print(letter_count)
Copy code

Output: 

2023_02_4.jpg

Explanation

Now you have 5 instances of c, 4 instances of r, and so on. You also have a new key-count pair, ‘t’: 1. Note that the iterable needs to be a sequence of items rather than a sequence of (key, count) pairs. 

Accessing Objects in Python Counter 

You should be aware that the Counter class has a similar interface as the built-in dict class. Most of the operations you can perform on a standard dictionary can also be performed on a Counter object. This includes accessing the values using dictionary-like key access (i.e. Counter [key]), as well as iterating over the keys, values, and items using methods such as keys(), values(), items(), and loops. 

Look at the examples below (continuation of the previous example):


 
from collections import Counter
letter_count = Counter("occurrences")
print(letter_count["c"])
print(letter_count["r"])
Copy code

Output: 

3

2


 
for letter in letter_count:
print(letter, letter_count[letter])
Copy code

Output: 

2023_02_5.jpg

 
for letter in letter_count.keys():
print(letter, letter_count[letter])
Copy code

Output: 

2023_02_6-6.jpg

 
for count in letter_count.values():
print(count)
Copy code

Output

 


 
for letter, count in letter_count.items():
  print(letter, count)
Copy code

Output

2023_02_7.jpg

Explanation

In the above examples, you can access and iterate over the keys (letter_count) and values (counts) of your Counter using the familiar dictionary interface, including the methods such as keys(),values(), and .items(). 

Endnotes 

When working with a large amount of data in Python, the Counter class from the collections module can efficiently count the number of occurrences of certain objects. This eliminates the need for more traditional techniques, such as loops and nested data structures, making your code cleaner and faster. This tutorial covered the following topics: 

  • Using different Python tools to count repeated objects. 
  • Creating counters quickly and efficiently using the Counter class. 
  • Retrieving the most common objects in a given counter. 

Want to learn more about Python and practice Python programming? Explore related articles here

Contributed by-Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio