Skip to content

Python Counter | Function

  • by

Python Counter is not a function, it is a container that holds the count of each of the elements that are available in the container. The dictionary class holds the Counter as the sub-class.

    class collections.Counter([iterable-or-mapping])

Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.

Counter function in Python

Simple example code takes iterable objects like lists, dictionaries, tuples, and strings as an argument and returns the count of each element.

from collections import Counter

List1 = ['a', 'b', 'a', 'a', 'c', 'd', 'b', 'c', 'd', 'a']

# Print count of the variable
print(Counter(List1))

Output:

Counter function in Python

Counter with String

from collections import Counter

my_str = "Hello world"

print(Counter(my_str))

Output: Counter({‘l’: 3, ‘o’: 2, ‘H’: 1, ‘e’: 1, ‘ ‘: 1, ‘w’: 1, ‘r’: 1, ‘d’: 1})

Counter with List

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

Output: Counter({‘x’: 4, ‘y’: 2, ‘z’: 2})

Counter with Dictionary

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2, 'z': 2}
print(Counter(dict1))

Output: Counter({‘x’: 4, ‘y’: 2, ‘z’: 2})

Counter with Tuple

from collections import Counter
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

Output: Counter({‘x’: 4, ‘y’: 2, ‘z’: 2})

Accessing, Initializing, Updating and deleting Counters

from collections import Counter

# Initializing Counter
print(Counter("Welcome!"))  # string
print(Counter(['x', 'y', 'z', 'x', 'x', 'x', 'y', 'z']))  # list
print(Counter({'x': 4, 'y': 2, 'z': 2}))  # dictionary
print(Counter(('x', 'y', 'z', 'x', 'x', 'x', 'y', 'z')))  # tuple

# Updating Counter
_count = Counter()
_count.update('Welcome!')
print(_count)

# Accessing Counter
print('%s : %d' % ('u', _count['u']))
print('\n')
for char in 'Welcome':
    print('%s : %d' % (char, _count[char]))

# Deleting an Element from Counter
dict1 = {'x': 4, 'y': 2, 'z': 2}
del dict1["x"]
print(Counter(dict1))

Output:

Counter({'e': 2, 'W': 1, 'l': 1, 'c': 1, 'o': 1, 'm': 1, '!': 1})
Counter({'x': 4, 'y': 2, 'z': 2})
Counter({'x': 4, 'y': 2, 'z': 2})
Counter({'x': 4, 'y': 2, 'z': 2})
Counter({'e': 2, 'W': 1, 'l': 1, 'c': 1, 'o': 1, 'm': 1, '!': 1})
u : 0


W : 1
e : 2
l : 1
c : 1
o : 1
m : 1
e : 2
Counter({'y': 2, 'z': 2})

How to Perform Arithmetic Operations on Python Counter

You can perform various arithmetic operations such as addition, subtraction, interaction, and union.

from collections import Counter

counter1 = Counter({'x': 4, 'y': 2, 'z': -2})

counter2 = Counter({'x1': -12, 'y': 5, 'z': 4})

# Addition
a = counter1 + counter2
print(a)

# Subtraction
s = counter1 - counter2
print(s)

# Intersection
i = counter1 & counter2
print(i)

# Union
u = counter1 | counter2
print(u)

Output:

Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})

Some Important Methods in Python Counter

  • elements(): This method will return all the elements with a count >0. Elements with 0 or -1 count will not be returned.
  • most_common(value): This method will return you the most common elements from the Counter list.
  • subtract(): This method is used to deduct the elements from another Counter.
  • update(): This method updates the elements from another Counter.
from collections import Counter

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

# elements()
_elements = c1.elements()  # get positive value and count>0
for a in _elements:
    print(a)

# most_common(value)
common_element = c1.most_common(2) # Most common element first followed by next
print(common_element)

# subtract()
c1.subtract(c2)
print(c1)

# update()
c1.update(c2)
print(c1)

Output:

x
x
x
x
x
y
y
[('x', 5), ('y', 2)]
Counter({'x': 3, 'x1': 0, 'z': -2, 'y': -3})
Counter({'x': 5, 'y': 2, 'x1': 0, 'z': -2})

Do comment if you have any doubts or suggestions on this Python function code.

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 *