Python Counter with Example & Python Collections Type
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
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, 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
Output
>>> c['a']
Output
>>> issubclass(Counter,dict)
Output
Now, let’s take a look at python counter syntax.
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:
1. 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
Output
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
Output
Or, you can pass it Python string.
>>> c=Counter("Hello") >>> c
Output
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
Output
2. 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
Output
3. Using Keyword Arguments
Finally, we can use keyword arguments to manually tell Counter() the count.
>>> c=Counter(a=3,b=2,c=1) >>> c
Output
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.update("Hello") >>> d
Output
We updated it once; we can update it further, in a different way if we want.
>>> d.update({'e':2,'o':4}) >>> d
Output
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.
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']
Output
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']
Output
1. 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()
Output
<itertools.chain object at 0x06336390>
We’ll discuss python itertools in a later lesson.
2. 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)
Output
[(‘a’, 3), (‘b’, 2)]
>>> e.most_common(4)
Output
[(‘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()
Output
[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)]
Reassigning Counts in Python
Of course, Python Counters aren’t immutable. You can reassign a count the following way:
>>> e['e']=5 >>> e
Output
Counter({‘e’: 5, ‘l’: 2, ‘H’: 1, ‘o’: 1})
To clear a Python counter, we use clear().
>>> b.clear() >>> b
Output
Counter()
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
Output
Counter({‘c’: 4, ‘a’: 3, ‘b’: 2, ‘d’: 2, ‘e’: 1})
>>> a-b
Output
Counter({‘a’: 3, ‘b’: 2})
>>> b-a
Output
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
Output
This way, it gives us negative counts if it has to.
Now, look at the following code:
>>> a.__add__(b)
Output
Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})
>>> a&b
Output
Counter({‘c’: 1})
>>> a|b
Output
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
Output
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.
Python Interview Questions on Python Counter
- What is a counter in Python?
- What does counter () do in Python?
- How do you write a count function in Python?
- How do you increment a counter in Python?
- How do you make a time counter in Python?
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.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google