Python Counter Module

FREE Online Courses: Click, Learn, Succeed, Start Now!

In this tutorial, we are going to learn about Python Counter Module. Let’s start!!!

What is Python Counter Class?

The counter is a class available in the Collections module. It is a subclass of dict.

Example of Counter in Python

from collections import Counter  # collections = module name 
                                 # Counter = class name
print(issubclass(Counter, dict)) # issubclass() = function name
# print() = function name, dict = class name

Output

True

We can use a counter to count the hashable objects. It counts the number of times each element appears in the given iterable and saves the elements and their counts as keys and values respectively.

Creating Python Counter Object

To create a counter object, we use the following syntax.

Syntax

obj = collections.Counter([iterable-or-mapping])

There are multiple ways for creating a counter object in Python. Let us see those in detail.

1. Creating a Counter Object using Iterables in Python

We can create a counter by passing an iterable like lists or tuples.

Example of counter in Python

from collections import Counter
c = Counter([1, 1, 1, 2, 3, 3, 4])
print(c)

Output

Counter({1: 3, 3: 2, 2: 1, 4: 1})

2. Creating a Counter Object using Strings in Python

Similar to iterables, we can also pass strings to create a counter object.

Example of counter in Python

from collections import Counter
c = Counter("PythonGeeks")
print(c)

Output

Counter({‘e’: 2, ‘P’: 1, ‘y’: 1, ‘t’: 1, ‘h’: 1, ‘o’: 1, ‘n’: 1, ‘G’: 1, ‘k’: 1, ‘s’: 1})

3. Creating a Counter Object using Dictionary in Python

We can create a counter object by passing a dictionary. This is useful when we want to explicitly define the counts of values. 

Example of counter in Python

from collections import Counter
c = Counter({"A": 2, "B": 1})
print(c)

Output

Counter({‘A’: 2, ‘B’: 1})

4. Creating a Counter Object using Keyword Arguments in Python

We can create a counter object by using the keyword arguments. This is comparable to using a dictionary. 

Example of counter in Python

from collections import Counter
c = Counter(A=2, B=1)
print(c)

Output

Counter({‘A’: 2, ‘B’: 1})

Getting Values from Python Counter Object

Since the Counter is a subclass of dictionary, the process of getting the count of a specific element from the Counter is similar to getting values from a dictionary. We just need to pass the element, to which we want to get the count, as an index to the counter.

Example of Counter in Python

from collections import Counter
c = Counter(['a', 'a', 'b', 'c'])
print(c['a'])

Output

2

Unlike a typical dictionary, Counter returns 0 (zero) instead of raising a KeyError, if the element that we passed is not in the counter.  

Example of Counter in Python

from collections import Counter
c = Counter(['a', 'a', 'b', 'c'])
print(c['d'])

Output

0

Modifying Values of Python Counter Object

A counter is a mutable object. This means that we can modify the count of an element in an existing counter object. This is similar to modifying the value of a key in a dictionary. 

Example of counter in Python

from collections import Counter

c = Counter(['a', 'a', 'b', 'c'])
print(c)
c['a'] = 1
c['c'] = 4
print(c)

Output

Counter({‘a’: 2, ‘b’: 1, ‘c’: 1})Counter({‘c’: 4, ‘a’: 1, ‘b’: 1})

We can also add new elements and their counts to an existing counter object by following the above method.

Example of counter in Python

from collections import Counter
c = Counter(['a', 'a', 'b', 'c'])
print(c)
c['d'] = 10
print(c)

Output

Counter({‘a’: 2, ‘b’: 1, ‘c’: 1})Counter({‘d’: 10, ‘a’: 2, ‘b’: 1, ‘c’: 1})

Methods of Python Counter Class

1. update([iterable-or-mapping])

This method is used to modify an existing counter object. We can use an iterable, string, dictionary, and keyword argument for this method. It counts the number of times an element occurs in the passed argument and adds the count to the existing counter object. If the element does not already exist in the counter object, it creates a new key-value pair and adds it to the counter object.

The method update() creates a new key-value pair and adds that new pair to the counter object.

Example of using update() in Python

from collections import Counter

c = Counter(['a', 'a', 'b', 'c'])
print(c)
c.update(['d', 'd', 'a', 'e'])
print(c)

Output

Counter({‘a’: 2, ‘b’: 1, ‘c’: 1})Counter({‘a’: 3, ‘d’: 2, ‘b’: 1, ‘c’: 1, ‘e’: 1})

We can also use this to fill up an empty counter object.

Example of using update() in Python

from collections import Counter

c = Counter()
print(c)
c.update(['d', 'd', 'a', 'e'])
print(c)

Output

Counter()Counter({‘d’: 2, ‘a’: 1, ‘e’: 1})

2. elements()

This method returns an iterator that we can use in for-loops to iterate over all elements and their counts in the counter object.

Example of using elements() in Python

from collections import Counter

c = Counter(['a', 'a', 'b', 'c'])
for ele in c.elements():
    print(f"{ele} - {c[ele]}")

Output

a – 2a – 2

b – 1

c – 1

3. most_common([n])

The method accepts an integer n and returns a list of the counter object’s n most frequent elements. It is sorted from most frequent elements to least frequent elements

Example of using most_common() in Python

from collections import Counter
c = Counter([1, 2, 1, 3, 1, 2, 1, 4, 1, 2])
print(c.most_common(2))

Output

[(1, 5), (2, 3)]

If no argument is passed, then it returns all elements and their counts sorted from most common to least common. 

Example of using most_common() in Python

from collections import Counter
c = Counter([1, 2, 1, 3, 1, 2, 1, 4, 1, 2])
print(c.most_common())

Output

[(1, 5), (2, 3), (3, 1), (4, 1)]

4. clear()

This method when called empties the entire counter object. 

Example of using clear() in Python

from collections import Counter

c = Counter([1, 2, 1, 3, 1, 2, 1, 4, 1, 2])
print(c)
c.clear()
print(c)

Output

Counter({1: 5, 2: 3, 3: 1, 4: 1})Counter()

Arithmetic Operations on Counter Objects in Python

We can also use different arithmetic operators on counter objects. Let us see this in detail.

1. Plus Operator (+)

This operator merges two counter objects. 

Example of using plus operator in Python

from collections import Counter

c1 = Counter(a=3, b=1, c=2)
print(c1)
c2 = Counter(c=1, d=2, e=3)
print(c2)
c3 = c1 + c2
print(c3)

Output

Counter({‘a’: 3, ‘c’: 2, ‘b’: 1})Counter({‘e’: 3, ‘d’: 2, ‘c’: 1})

Counter({‘a’: 3, ‘c’: 3, ‘e’: 3, ‘d’: 2, ‘b’: 1})

Alternatively, we can also use the magic method __add__ to perform this operation. 

Example of using plus operator in Python

from collections import Counter

c1 = Counter(a=3, b=1, c=2)
print(c1)
c2 = Counter(c=1, d=2, e=3)
print(c2)
c3 = c1.__add__(c2)
print(c3)

Output

Counter({‘a’: 3, ‘c’: 2, ‘b’: 1})Counter({‘e’: 3, ‘d’: 2, ‘c’: 1})

Counter({‘a’: 3, ‘c’: 3, ‘e’: 3, ‘d’: 2, ‘b’: 1})

2. Minus Operator (-)

This operator subtracts the second counter object from the first counter object. 

Example of using minus operator in Python

from collections import Counter

c1 = Counter(a=3, b=1, c=2)
print(c1)
c2 = Counter(c=1, d=2, e=3)
print(c2)
c3 = c1 - c2
print(c3)

Output

Counter({‘a’: 3, ‘c’: 2, ‘b’: 1})Counter({‘e’: 3, ‘d’: 2, ‘c’: 1})

Counter({‘a’: 3, ‘b’: 1, ‘c’: 1})

3. And Operator (&)

The method returns a counter object with only the items that are present in both counter objects.

Example of using and operator in Python

from collections import Counter

c1 = Counter(a=3, b=1, c=2)
print(c1)
c2 = Counter(c=1, d=2, e=3)
print(c2)
c3 = c1 & c2
print(c3)

Output

Counter({‘a’: 3, ‘c’: 2, ‘b’: 1})Counter({‘e’: 3, ‘d’: 2, ‘c’: 1})

Counter({‘c’: 1})

4. Or Operator (|)

The method returns a counter object with the items that are present in any of the counter objects. This is a bit similar to the plus operator but unlike the plus operator, it does not add the counts of elements. 

Example of using or operator in Python

from collections import Counter

c1 = Counter(a=3, b=1, c=2)
print(c1)
c2 = Counter(c=1, d=2, e=3)
print(c2)
c3 = c1 | c2
print(c3)

Output

Counter({‘a’: 3, ‘c’: 2, ‘b’: 1})Counter({‘e’: 3, ‘d’: 2, ‘c’: 1})

Counter({‘a’: 3, ‘e’: 3, ‘c’: 2, ‘d’: 2, ‘b’: 1})

Interview Questions on Python Counter Module

Q1. Write a program to print the counts of all elements in this list [s, s, 9, s, 7, s, 9, 8, 9, s ].

Ans 1. Complete code is as follows:

from collections import Counter

li = ['s', 's', 9, 's', 7, 's', 9, 8, 9, 's']
c = Counter(li)
print(c)

Output

Counter({‘s’: 5, 9: 3, 7: 1, 8: 1})

Q2. Write a program to print the number of times the element “o’’ occurs in the string “Yellowwooddoor”. 

Ans 2. Complete code is as follows:

from collections import Counter

s = 'Yellowwooddoor'
c = Counter(s)
print(c['o'])

Output

5

Q3. Sam gave his phone number 3453333332 to John. John wants to find how many ‘3’s in Sam’s phone number. Write a program to John print the count of 3.  

Ans 3. Complete code is as follows:

from collections import Counter

phone_number = 3453333332
c = Counter(str(phone_number))
print(c['3'])

Output

7

Q4. Write a program to print an empty counter object.

Ans 4.  Complete code is as follows:

from collections import Counter
c = Counter({1:2, 2:3})
c.clear()
print(c)

Output

Counter()

Q5. Write a program to merge two counter objects,

Ans 5. Complete code is as follows:

from collections import Counter

counterA = Counter('Yellowwooddoor')
counterB = Counter('Bookkeeper')
counterC = counterA + counterB
print(counterC)

Output

Counter({‘o’: 7, ‘e’: 4, ‘l’: 2, ‘w’: 2, ‘d’: 2, ‘r’: 2, ‘k’: 2, ‘Y’: 1, ‘B’: 1, ‘p’: 1})

Conclusion

In this article, we learned how to create counters and how to use them, and their methods. We also learned different arithmetic operations that can be performed on counter objects. Furthermore, please share any issues or queries in the comments area.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


Leave a Reply

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