Python Counter with Example & Python Collections Type

1. Python Counter Tutorial

Earlier, we discussed three classes from Python module collections. Today, we’ll talk about another such class- Python Counter. Here, we will study initializing, updating, accessing, and reassigning counters in Python. Moreover, we will learn Python counter list, loops and arithmetic.

So, let’s start the Python Counter Tutorial.

What is Python Counter

Python Counter with Example & Python Collections Type

2. Introduction to Python Counter

Python Counter, like the other three containers we mentioned above, is a subclass of ‘dict’. It keeps a count of the number of occurrences of any value in the container. Simply speaking, if you add the value ‘hello’ thrice in the container, it will remember that you added it thrice. So, Counter counts hashable objects in Python. Lets see this Python Counter example.

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

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

>>> c['a']

3

>>> issubclass(Counter,dict)

True
Now, let’s take a look at python counter syntax.

3. Initializing a Python Counter

To initialize or define a counter in python, we use the counter factory function. Yet, in that, we can do it in three ways:

a. Using a List or Similar Containers

We can pass Python list of values to Counter(). Every time it encounters a value again, it raises its count by 1.

>>> c=Counter(['a','b','c','a','b','a'])
>>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})
As you can see, it could recognize that there are three ‘a’s in the list in python, two ‘b’s, and one ‘c’.
We can also use Python tuple.

>>> c=Counter(('a','b','c','a','b','a'))
>>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})
Or, you can pass it Python string.

>>> c=Counter("Hello")
>>> c

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})
Python string is a container too, remember? Also, it displays the counts in a descending order. But when we use a Set, it only holds every value once. So, it does not make sense to use Counter() with Python Set.

>>> c=Counter({'a','b','c','a','b','a'})
>>> c

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

b. Using a Python Dictionary

We can also manually tell the Python Counter the count of values, using a dictionary in Python.

>>> c=Counter({'a':3,'b':2,'c':1})
>>> c

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

c. Using Keyword Arguments

Finally, we can use keyword arguments to manually tell Counter() the count.

>>> c=Counter(a=3,b=2,c=1) >>> c

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

4. Updating a Python Counter

Like it is with every other container, we can first declare an empty Python Counter and then populate it. We perform the update calling the update() method on the Counter.

>>> d=Counter()
>>> d Counter()
>>> d.update("Hello")
>>> d

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})
We updated it once; we can update it further, in a different way if we want.

>>> d.update({'e':2,'o':4})
>>> d

Counter({‘o’: 5, ‘e’: 3, ‘l’: 2, ‘H’: 1})
Here, we told Python Counter that we’re adding two more ‘e’s and four more ‘o’s. Then, when we accessed it, it printed the counts in a descending order.

5. Accessing Counts in Python

We can access the count for a particular value simply by using it as an index to the Python Counter we defined.

>>> d['e']

3
Let’s try displaying the counts of values in a string, with Python counter that takes a different string as an argument.

>>> e=Counter("Hello")
>>> for i in "Help":                
          print(f"{i}: {e[i]}")         
H: 1
e: 1
l: 2
p: 0

From this, we interpret that in Python Counter e, ‘H’ has a count of 1, ‘e’ has a count of 1, ‘l’ has 2, and ‘p’ has none(hence, 0).
From this, we conclude that if a key doesn’t exist, it will consider its count to be 0, instead of raising a KeyError.

>>> e['q']

To compare, let’s also see how this would fair in a regular dictionary.

>>> dict1={'H':1,'e':1,'l':2,'o':1}
>>> dict1['p']
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
dict1['p']

KeyError: ‘p’

a. The elements() Method

Or, we could use the elements() method, which returns an iterator object for the values in the Counter. We can use this with a Python for-loop.

>>> e=Counter({'a':3,'b':2,'c':1,'d':0})
>>> for i in e.elements():
                print(f"{i}: {e[i]}")
a: 3
a: 3
a: 3
b: 2
b: 2
c: 1
>>> e.elements()

<itertools.chain object at 0x06336390>
We’ll discuss python itertools in a later lesson.

b. Accessing the Most Common Values

To get n most-common values (the ones with the highest frequencies), we call the method most_common().

>>> e.most_common(2)
[(‘a’, 3), (‘b’, 2)]
>>> e.most_common(4)
[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)] When we call it without any argument, however, we get all the items. So, it is the same as calling it with an argument with a value equal to the number of elements in Python counter.

>>> e.most_common()
[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)]

6. Reassigning Counts in Python

Of course, Python Counters aren’t immutable. You can reassign a count the following way:

>>> e['e']=5
>>> e

Counter({‘e’: 5, ‘l’: 2, ‘H’: 1, ‘o’: 1})
To clear a Python counter, we use clear().

>>> b.clear()
>>> b

Counter()

Python Interview Questions

7. Python Counter Arithmetic

Finally, we’ll discuss some Counter arithmetic in Python.
To aggregate results, we can perform arithmetic and set operations on Python Counters. Let’s take two sample Counters for exemplary purposes.

>>> a=Counter({'a':3,'b':2,'c':1})
>>> b=Counter({'c':3,'d':2,'e':1})

Now, sit back and watch it unfold.

>>> a+b

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

>>> a-b

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

>>> b-a

Counter({‘c’: 2, ‘d’: 2, ‘e’: 1})
Here, a-b does not have ‘c’, because 1-3=-2. A negative count does not mean anything. Likewise, b-a has ‘c’ with a count of 2, because 3-1=2. We can also do this calling the subtract() method.

>>> a.subtract(b)
>>> a

Counter({‘a’: 3, ‘b’: 2, ‘e’: -1, ‘c’: -2, ‘d’: -2})
This way, it gives us negative counts if it has to.
Now, look at the following code:

>>> a.__add__(b)

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

>>> a&b

Counter({‘c’: 1})

>>> a|b

Counter({‘a’: 3, ‘c’: 3, ‘b’: 2, ‘d’: 2, ‘e’: 1})
Here, a|b has a count of 3 for ‘c’, because that is what OR does.

>>> a=Counter({'e':-1})
>>> -a

Counter({‘e’: 1})
If you’ve forgotten about these operators, read up on Python Operators.
Check out the result for dir(Counter), and try to apply all of those methods to your Counters in Python.

8. Conclusion

Python Counter is a container that keeps track of the number of occurrences of a value. Today, we looked at methods like update(), most_common(), clear(), elements(), and subtract(). In our next lesson, we’ll revise all these four classes in brief.
See Also- Python Advantages and Disadvantages & Top books to learn Python
For reference

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.