Python collections Counter
Last Updated : 18 Dec, 2024
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])
Initialization:
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
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.
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
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)
The elements() method returns an iterator that produces all elements in the Counter.
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)
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})
The 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 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
Collections.UserList in Python
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
2 min read
Garbage Collection in Python
Garbage Collection in Python is an automatic process that handles memory allocation and deallocation, ensuring efficient use of memory. Unlike languages such as C or C++ where the programmer must manually allocate and deallocate memory, Python automatically manages memory through two primary strateg
5 min read
Python len() Function
The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example: [GFGTABS] Python s = "G
2 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:
2 min read
Python | Operator.countOf
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. Syntax : Operator.countOf(freq = a, value = b) Parameters : freq : It can be list or any other data type which store value value : It is value for which we have to count the num
2 min read
numpy.count() in Python
numpy.core.defchararray.count(arr, substring, start=0, end=None): Counts for the non-overlapping occurrence of sub-string in the specified range. Parameters: arr : array-like or string to be searched. substring : substring to search for. start, end : [int, optional] Range to search in. Returns : An
1 min read
Convert integer to string in Python
In this article, weâll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function. Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string. [GFGTABS] Python n = 42
2 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