Skip to content

From collections import Counter in Python

  • by

Using the Python collections Counter can count the key-value pairs in an object, also called a hashtable object. You have to import the counter tool From collections module in python.

from collections import Counter
Counter(list)

The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.

From collections import Counter in Python

Simple example code import Counter. You can simply import it the same as other modules.

Python Counter takes in input a list, tuple, dictionary, and string, which are all iterable objects, and it will give you output that will have the count of each element.

from collections import Counter

list1 = ['x', 'y', 'z', 'x', 'x', 'x', 'y', 'z']

res = Counter(list1)
print(res)
print(type(res))

Output:

From collections import Counter in Python

More examples: Python Counter | Function

Do comment if you have any doubts or suggestions on this Python counter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *