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:

True

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:

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

Code:

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

Output:

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

Code:

>>> Counter(A=3, B=2, C=1, D=4)

Output:

Counter({‘D’: 4, ‘A’: 3, ‘B’: 2, ‘C’: 1})

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:

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

The update() method lets us add sequences or dictionaries or keyword arguments later.

Code:

>>> nums.update({1:2,2:2})
>>> nums

Output:

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

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:

<itertools.chain object at 0x00000210EF4C4248>

Code:

>>> for elem in c.elements():
  print(elem)

Output:

A
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:

Counter({‘D’: 4, ‘A’: 3, ‘C’: 1})

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:

4

Code:

>>> c=Counter(A=3, B=2, C=1, D=4)
>>> c['B']

Output:

2

Code:

>>> c['E']

Output:

0

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:

A 3
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:

Counter({‘B’: 4, ‘D’: 4, ‘A’: 3, ‘C’: 1})

You can also clear the counts with the clear() method.

Code:

>>> c.clear()
>>> c

Output:

Counter()

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:

[(‘D’, 4), (‘F’, 4), (‘A’, 3), (‘B’, 2), (‘E’, 2), (‘C’, 1)]

Code:

>>> c.most_common(1)

Output:

[(‘D’, 4)]

Code:

>>> c.most_common(2)

Output:

[(‘D’, 4), (‘F’, 4)]

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:

Counter({‘D’: 9, ‘A’: 5, ‘B’: 5, ‘F’: 4, ‘E’: 3, ‘C’: 2})

Code:

>>> c1-c2

Output:

Counter({‘A’: 1, ‘E’: 1})

Code:

>>> c2-c1

Output:

Counter({‘F’: 4, ‘B’: 1, ‘D’: 1})

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:

Counter({‘D’: 4, ‘A’: 3, ‘B’: 2, ‘E’: 2, ‘C’: 1})

We can ‘and’ and ‘or’ counters.

Code:

>>> c1&c2

Output:

Counter({‘A’: 1, ‘E’: 1})

Code:

>>> c1|c2

Output:

Counter({‘D’: 5, ‘F’: 4, ‘B’: 3, ‘A’: 2, ‘C’: 1, ‘E’: 1})

But we cannot XOR them.

Code:

>>> c1^c2

Output:

Traceback (most recent call last):
  File “<pyshell#50>”, line 1, in <module>
    c1^c2
TypeError: unsupported operand type(s) for ^: ‘Counter’ and ‘Counter’

We can also use the unaryoperator with a counter.

Code:

>>> c1

Output:

Counter({‘A’: 1, ‘E’: 1, ‘C’: 0, ‘B’: -1, ‘D’: -1, ‘F’: -4})

Code:

>>> -c1

Output:

Counter({‘F’: 4, ‘B’: 1, ‘D’: 1})

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.