What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Understand Python Counter in Collections (with Examples)

  • May 06, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Understand Python Counter in Collections (with Examples)

The Counter in Python is a useful tool in scenarios where counting the frequency of elements is required. In this article, we will learn about Python Counter and its various functionalities in detail.

What is Python Counter?

Python Counter is a built-in class that allows you to count the occurrences of elements in an iterable object, like a list, tuple, or string. You can use it to perform many common operations like counting the frequency of elements or finding the most common elements. It is a part of the 'collections' module.

Like we have tally tables that count the number of the same elements in a group of elements, the counter keeps a count of the number of the same elements in a collection. 

Python Collection Counter

Python collections module provides various container classes, which are alternatives to the built-in Python containers such as list, tuple, and dict. One of the container classes provided by the collections module is Counter.

It is a subclass of dict that is designed to count the occurrences of elements in a collection. It takes an iterable as input and returns a dictionary-like object with the elements of the iterable as keys and their count as values. It can be useful in various scenarios, such as counting the frequency of words in a text or counting the number of occurrences of different categories in a dataset.

What is counter() function?

Python's counter() function is a built-in tool that enables developers to perform quick and efficient counting operations. It operates on iterables, including strings, lists, and dictionaries. The function creates a dictionary that maps each element in the iterable to its count or frequency in the collection.

The function takes an iterable as its input and generates a dictionary as its output. The keys in the dictionary represent the unique elements in the iterable, and their corresponding values represent the number of occurrences of each element in the collection.

One of the most significant benefits of the counter() function is that it saves developers time and effort, as they do not need to manually count the frequency of each element in the iterable. It is also useful for tasks such as word frequency analysis and identifying the most common elements in a dataset.

from collections import Counter
my_list =['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
my_counter = Counter(my_list)
print(my_counter)

 

Output:

Counter({'apple': 3, 'banana': 2, 'orange': 1})

 

As you can see, the Counter has counted the number of times each fruit appears in the list.

Python's Counter is helpful for a wide range of applications. It can be used to count the number of times a word appears in a text file, the number of times a user clicks a button in your GUI application, or the quantity of a certain code mistake.

To count the number of times a word appears in a text file, you could use a Counter as shown in the following example:

from collections import Counter

with open('my_text_file.txt') as f:
    word_count = Counter(f.read().split())

print(word_count)

 

In this example, we open a text file, read it, then divide it into a list of terms. The result is printed once we generate a Counter from that list. The result will be a dictionary-like object with information on the frequency of each word in the text file.

Using counter in while loop

Using a Counter in a while loop can be helpful when you need to repeatedly count the frequency of elements until a certain condition is met. For example, you could use a while loop to continuously read in values from a file or user input, and then use a Counter to keep track of how many times each value appears.

To use a Counter in a while loop, you first need to initialize an empty Counter object outside of the loop. Inside the loop, you can use the update() method to increment the count of each element in the Counter. You can then exit the loop when a certain condition is met, such as reaching the end of a file or receiving a specific user input.

Once you exit the loop, you can iterate over the Counter object to retrieve the frequency of each element. You can use the items() method to obtain a list of (element, frequency) tuples, which you can then print or manipulate as needed.

from collections import Counter
my_list = [1, 2, 3, 1, 2, 3, 4, 5, 1, 2, 3]
my_counter = Counter(my_list)
i=0
while i < len(my_list):
  print(my_list[i], ":", my_counter[my_list[I]])
  i += 1

 

Output:

1 : 3
2 : 3
3 : 3
1 : 3
2 : 3
3 : 3
4 : 1
5 : 1
1 : 3
2 : 3
3 : 3

 

The code creates a list of integers called my_list with multiple occurrences of some elements. It then creates a Counter object called my_counter that counts the frequency of each element in my_list. The while loop iterates over the indices of my_list and prints the element at that index followed by its frequency as determined by the my_counter object.

Since the Counter object is created based on the elements of the my_list, it can be used to quickly determine the frequency of each element in the list without the need for explicit counting. The output shows the element at each index of my_list followed by its frequency, with duplicates of the same element showing up multiple times because of the while loop.

What is the difference between Counter and count in Python?

While both of these are sued to count the frequency of elements, there are definitely some differences between counter and count. The count method returns the number of times a given element appears in the sequence, whereas the counter class returns a dictionary containing the counts as key-value pairs.

So, you should use the count method when you need to count the number of times a specific element appears in a sequence. But if you want to count the occurrences of all elements in an iterable object, use the other one.

Conclusion

In conclusion, you now know everything about Python Counter is a valuable tool for data analysis and provides an efficient way to count the frequency of elements in a collection. It is a container data type that counts the frequency of elements in a collection. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.