Python collections Counter
Counters are a subclass of the dict class in Python collections module. They are getting 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:
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)
Counter({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:
Table of Content
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.
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)
Counter({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 distinct types of iterables.
Accessing Counter Elements
We can access the count of each element using the element when the key. If an element is not in the Counter, it returns 0.
Example:
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)
1 2 3 0
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() functions/method to achieve this.
Example:
from collections import Counter
ctr = Counter([1, 2, 2])
# Adding new elements
ctr.update([2, 3, 3, 3])
print(ctr)
Counter({2: 3, 3: 3, 1: 1})
Counter Methods
elements(): Returns an iterator over elements repeating each when many times when its count. Elements are returned in arbitrary order.
from collections import Counter
ctr = Counter([1, 2, 2, 3, 3, 3])
items = list(ctr.elements())
print(items)
[1, 2, 2, 3, 3, 3]
The elements() functions/method returns an iterator that produces all elements in the Counter.
most_common(): Returns a list of the n most popular elements and their counts from the most popular to the least. If n is not specified, it returns all elements in the Counter.
from collections import Counter
ctr = Counter([1, 2, 2, 3, 3, 3])
common = ctr.most_common(2)
print(common)
[(3, 3), (2, 2)]
subtract(): Subtracts element counts from another iterable or mapping. Counts can go negative.
from collections import Counter
ctr = Counter([1, 2, 2, 3, 3, 3])
ctr.subtract([2, 3, 3])
print(ctr)
Counter({1: 1, 2: 1, 3: 1})
The subtract() functions/method decreases the counts for elements found in another iterable.
Arithmetic Operations enabled Counters
Counters support addition, subtraction, intersection union operations, allowing for various arithmetic operations.
Example:
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)
Counter({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 may be interested to learn more about accessing counters in Python, the article (Accessing Counters) is a great resource.
Counters in Python | More detail
Once initialized, counters are accessed just similar as dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown when 0.
Example: In this example, we are using Counter to print the key and frequency of that key. The elements present inside the frequency map are printed along with their frequency and if the element is not present inside the Counter map, then the element will be printed along with 0.
Python3
from collections import Counter # Create a list z = [ 'blue' , 'red' , 'blue' , 'yellow' , 'blue' , 'red' ] col_count = Counter(z) print (col_count) col = [ 'blue' , 'red' , 'yellow' , 'green' ] # Here green is not in col_count # so count of green will be zero for color in col: print (color, col_count[color]) |
Output: <
Counter({‘blue’: 3, ‘red’: 2, ‘yellow’: 1})
blue 3
red 2
yellow 1
green 0
elements() functions/method of Counter in Python
The elements() functions/method returns an iterator that produces all of the items known to the Counter. Note: Elements with count <= 0 are not included.
Example : In this example, the elements inside the Counter would be printed by using the elements() functions/method of Counter.
Python3
# Python example to demonstrate elements() from collections import Counter coun = Counter(a = 1 , b = 2 , c = 3 ) print (coun) print ( list (coun.elements())) |
Output :
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']
most_common() functions/method of Counter in Python
most_common() is have used to produce a sequence of the n most Common encountered input values and their respective counts. If the parameter ‘n’ is not specified or None is passed when the parameter most_common() returns a list of all elements and their counts.
Example: In this example, the element with the most frequency is printed followed by the next-most frequent element by using most_common() functions/method inside Counter in Python.
Python3
from collections import Counter coun = Counter(a = 1 , b = 2 , c = 3 , d = 120 , e = 1 , f = 219 ) # This prints 3 most frequent characters for letter, count in coun.most_common( 3 ): print ( '%s: %d' % (letter, count)) |