Python Counter – Learn to create, access, and assign counters in Python
In this article, we will talk about Counter in Python. This is a class in the collections module.
Other classes are defaultdict, OrderedDict and namedtuple. Let’s first discuss the concept of Python counter.
What is a Counter in Python?
A counter is a container in the collections module. It is a subclass of dict and it is an unordered collection in which elements and their counts are stored as a dictionary.
Code:
>>> from collections import Counter >>> issubclass(Counter,dict)
Output:
Creating a Python Counter
We can create a counter with a parameter that can be:
- A sequence of items – like a list or tuple or string.
- Dictionary with keys and counts.
- Keyword arguments with string names and counts.
Let’s take an example.
Code:
>>> Counter([1, 2, 1, 3, 4, 2, 1, 1])
Output:
Code:
>>> Counter({1:4, 2:2, 3:1, 4:1})
Output:
Code:
>>> Counter(A=3, B=2, C=1, D=4)
Output:
Updating a Counter in Python
If you don’t know the elements to add in a counter, you can create an empty counter and add them later.
Code:
>>> nums=Counter() >>> nums.update([1,2,1,3,4,2,1,1]) >>> nums
Output:
The update() method lets us add sequences or dictionaries or keyword arguments later.
Code:
>>> nums.update({1:2,2:2}) >>> nums
Output:
It does not replace the counts in the counter, it adds to them.
Accessing Elements in Python Counter
To get the list of elements in the counter we can use the elements() method. It returns an iterator object for the values in the Counter.
Code:
>>> c=Counter(A=3, B=2, C=1, D=4) >>> c.elements()
Output:
Code:
>>> for elem in c.elements(): print(elem)
Output:
A
A
B
B
C
D
D
D
D
To delete an element, you can use the del keyword.
Code:
>>> del c['B'] >>> c
Output:
Accessing Counts in Python Counter
We can use indexing to access the counts in a Python counter. Whatever element we want to get the count of, we will use it as the index.
Code:
>>> nums[2]
Output:
Code:
>>> c=Counter(A=3, B=2, C=1, D=4) >>> c['B']
Output:
Code:
>>> c['E']
Output:
E is not in the counter object, so it returns 0. This raises a KeyError for dictionaries. We can also get the counts of all items in a sequence.
Code:
>>> for val in 'ABCD': print(val, c[val])
Output:
B 2
C 1
D 4
Reassigning Counts in Python Counter
The update() method adds to the counts in the Python counter but does not replace them. If you want to replace them, you can use the assignment operator.
Code:
>>> c=Counter(A=3, B=2, C=1, D=4) >>> c['B']=4 >>> c
Output:
You can also clear the counts with the clear() method.
Code:
>>> c.clear() >>> c
Output:
Getting Most Common Values in Python Counter
The most_common() method gives us the most common values in the Python counter. These are the values with the highest counts in the counter.
Code:
>>> c=Counter(A=3, B=2, C=1, D=4, E=2, F=4) >>> c.most_common()
Output:
Code:
>>> c.most_common(1)
Output:
Code:
>>> c.most_common(2)
Output:
D and F are the most common values in this counter.
If we do not provide a parameter value, it prints all values and their counts.
Python Counter Arithmetic
Like we add the integers 2 and 3, we can perform counter arithmetic on counters.
Let’s take two counters.
Code:
>>> c1=Counter(A=3, B=2, C=1, D=4, E=2) >>> c2=Counter(A=2, B=3, C=1, D=5, E=1, F=4)
Code:
>>> c1+c2
Output:
Code:
>>> c1-c2
Output:
Code:
>>> c2-c1
Output:
Counters can have negative counts too.
The subtract() method gives us negative counts too but the – operator doesn’t. Now we can add c2 back to c1.
Code:
>>> c1.__add__(c2)
Output:
We can ‘and’ and ‘or’ counters.
Code:
>>> c1&c2
Output:
Code:
>>> c1|c2
Output:
But we cannot XOR them.
Code:
>>> c1^c2
Output:
File “<pyshell#50>”, line 1, in <module>
c1^c2
TypeError: unsupported operand type(s) for ^: ‘Counter’ and ‘Counter’
We can also use the unary – operator with a counter.
Code:
>>> c1
Output:
Code:
>>> -c1
Output:
B, D, and F had negative counts so now their counts are positive. And it doesn’t show the counts for A, C, and E because they are negative.
Summary
In this Python counter tutorial, we learned about counters in Python. We saw how to create them, update them, access elements, access counts, reassign counts, get the most common values and perform counter arithmetic.