Python Collections Counter
Last Updated : 12 Jun, 2025
Counters are a subclass of the dict class in Python collections module. They are used to count the occurrences of elements in an iterable or to count the frequency of items in a mapping. Counters provide a clean and efficient way to tally up elements and perform various operations related to counting.
Example:
Python from collections import Counter # Example list of elements val = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] # Creating a Counter ctr = Counter(val) print(ctr)
OutputCounter({4: 4, 3: 3, 2: 2, 1: 1})
In this example, the Counter counts the occurrences of each element in the list.
Let's take a look at counters in Python in detail:
Syntax
class collections.Counter([iterable-or-mapping])
Parameters: The constructor of the counter can be called in any one of the following ways:
- With a sequence of items
- With a dictionary containing keys and counts
- With keyword arguments mapping string names to counts
Return Type: it returns a "collections.counter" object (functionally its a dictionary-like object)
Creating a Counter
To use a Counter, we first need to import it from the collections module.
Python from collections import Counter # Creating a Counter from a list ctr1 = Counter([1, 2, 2, 3, 3, 3]) # Creating a Counter from a dictionary ctr2 = Counter({1: 2, 2: 3, 3: 1}) # Creating a Counter from a string ctr3 = Counter('hello') print(ctr1) print(ctr2) print(ctr3)
OutputCounter({3: 3, 2: 2, 1: 1}) Counter({2: 3, 1: 2, 3: 1}) Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
In these examples, we create Counters from different types of iterables.
Refer to collection module to learn in detail.
Accessing Counter Elements
We can access the count of each element using the element as the key. If an element is not in the Counter, it returns 0.
Example:
Python from collections import Counter ctr = Counter([1, 2, 2, 3, 3, 3]) # Accessing count of an element print(ctr[1]) print(ctr[2]) print(ctr[3]) print(ctr[4]) # (element not present)
This example shows how to access the count of specific elements in the Counter.
Updating counters
Counters can be updated by adding new elements or by updating the counts of existing elements. We can use the update() method to achieve this.
Example:
Python from collections import Counter ctr = Counter([1, 2, 2]) # Adding new elements ctr.update([2, 3, 3, 3]) print(ctr)
OutputCounter({2: 3, 3: 3, 1: 1})
Counter Methods
1. elements()
Returns an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order.
Python from collections import Counter ctr = Counter([1, 2, 2, 3, 3, 3]) items = list(ctr.elements()) print(items)
Explanation: elements() method returns an iterator that produces all elements in the Counter.
2. most_common()
Returns a list of the n most common elements and their counts from the most common to the least. If n is not specified, it returns all elements in the Counter.
Python from collections import Counter ctr = Counter([1, 2, 2, 3, 3, 3]) common = ctr.most_common(2) print(common)
3. subtract()
Subtracts element counts from another iterable or mapping. Counts can go negative.
Python from collections import Counter ctr = Counter([1, 2, 2, 3, 3, 3]) ctr.subtract([2, 3, 3]) print(ctr)
OutputCounter({1: 1, 2: 1, 3: 1})
Explanation: subtract() method decreases the counts for elements found in another iterable.
Arithmetic Operations on Counters
Counters support addition, subtraction, intersection union operations, allowing for various arithmetic operations.
Example:
Python from collections import Counter ctr1 = Counter([1, 2, 2, 3]) ctr2 = Counter([2, 3, 3, 4]) # Addition print(ctr1 + ctr2) # Subtraction print(ctr1 - ctr2) # Intersection print(ctr1 & ctr2) # Union print(ctr1 | ctr2)
OutputCounter({2: 3, 3: 3, 1: 1, 4: 1}) Counter({1: 1, 2: 1}) Counter({2: 1, 3: 1}) Counter({2: 2, 3: 2, 1: 1, 4: 1})
If you want to learn more about accessing counters in Python, the article (Accessing Counters) is a great resource.
Similar Reads
Python collections Counter Counters are a subclass of the dict class in Python collections module. They are used to count the occurrences of elements in an iterable or to count the frequency of items in a mapping. Counters provide a clean and efficient way to tally up elements and perform various operations related to countin
4 min read
Python Collections Module The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
13 min read
Python time.perf_counter_ns() Function Python time.perf_counter_ns() function gives the integer value of time in nanoseconds. Syntax: from time import perf_counter_ns We can find the elapsed time by using start and stop functions. We can also find the elapsed time during the whole program by subtracting stoptime and starttime Example 1:
1 min read
Python - Itertools.count() Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code. Itertools provide us with functions for creating infinite sequences and itertools.count() is one such function and it does exactly what it sounds like, it co
3 min read
Numpy count_nonzero method | Python numpy.count_nonzero() function counts the number of non-zero values in the array arr. Syntax : numpy.count_nonzero(arr, axis=None) Parameters : arr : [array_like] The array for which to count non-zeros. axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is
1 min read
Python | Counter Objects | elements() Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
6 min read