Skip to content

Python Counter methods

  • by

There are some important methods available with Python Counter, here is the list of same:

  • elements(): returns all the elements with a count >0. Elements with 0 or -1 count will not be returned.
  • most_common(value): returns the most common elements from the Counter list.
  • subtract(): used to deduct the elements from another Counter.
  • update(): used to update the elements from another Counter.

Python Counter methods

Simple example code of commonly used methods in Counter.

elements() method – This method returns the count element which are greater than 0. The elements with 0 or -1 will be completely omitted.

from collections import Counter

counter1 = Counter({'x': 5, 'y': 2, 'z': -2, 'x1': 0})

_elements = counter1.elements()
for a in _elements:
    print(a)

Output:

Python Counter methods

most_common(value) – It returns the most common elements from Counter list.

from collections import Counter

C1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})

res1 = C1.most_common(2)
print(res1)

res2 = C1.most_common()
print(res2)

Output:

[('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

subtract() method – It returns the new Counter object after performing subtraction. Let’s understand the following example.

from collections import Counter

c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})

c1.subtract(c2)
print(c1)

Output: Counter({‘y’: 7, ‘x’: 3, ‘x1’: 0, ‘z’: -2})

update()

from collections import Counter

c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})

c1.update(c2)
print(c1)

Output: Counter({‘y’: 17, ‘x’: 7, ‘x1’: 0, ‘z’: -2})

Do comment if you have any doubts or suggestions on this Python counter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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