Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python Counter in collections – Efficient Counting, Updating, and Arithmetic Operations

What is Python Counter?

Python’s Counter is a specialized container that counts the occurrences of each element in an iterable. It inherits from dict and stores elements as keys with their counts as values, making it an ideal tool for hash‑table‑style counting.

Why Use Python Counter?

Getting Started with Counter

Import the class from collections:

from collections import Counter

Now you can pass any iterable to Counter and receive a count mapping.

Example – Counting a List

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

Output:

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

Example – Counting a String

my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))

Output:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

Example – Counting a Dictionary

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

Output:

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

Example – Counting a Tuple

tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

Output:

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

Initializing, Updating, and Accessing Counters

Initializing

print(Counter("Welcome to Guru99 Tutorials!"))   # string
print(Counter(['x','y','z','x','x','x','y','z'])) # list
print(Counter({'x': 4, 'y': 2, 'z': 2}))          # dict
print(Counter(('x','y','z','x','x','x','y','z'))) # tuple
# Empty counter
_count = Counter()

Updating

_count.update('Welcome to Guru99 Tutorials!')
print(_count)

Output:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

Accessing Counts

print('%s : %d' % ('u', _count['u']))
for char in 'Guru':
    print('%s : %d' % (char, _count[char]))

Output:

u : 3
G : 1
u : 3
r : 2
u : 3

Deleting an Element

del _count['x']
print(_count)

Output:

Counter({'y': 2, 'z': 2})

Arithmetic Operations

Counter supports set‑like arithmetic. Positive counts are preserved; negative values are discarded in the result.

counter1 = Counter({'x': 4, 'y': 2, 'z': -2})
counter2 = Counter({'x1': -12, 'y': 5, 'z': 4})
# Addition
print(counter1 + counter2)
# Subtraction
print(counter1 - counter2)
# Intersection
print(counter1 & counter2)
# Union
print(counter1 | counter2)

Output:

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

Key Methods

Using elements()

counter = Counter({'x': 5, 'y': 2, 'z': -2, 'x1': 0})
for e in counter.elements():
    print(e)

Output:

x
x
x
x
x
y
y

Using most_common()

counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter.most_common(2))
print(counter.most_common())

Output:

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

Using subtract()

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})

Using update()

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})

Reassigning Counts

counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
counter['y'] = 20
print(counter)

Output:

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

Getting and Setting Element Counts

counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter['y'])
counter['y'] = 20
counter['y1'] = 10
print(counter)

Output:

12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

Summary

Python

  1. Python OOP Fundamentals: Classes, Objects, Inheritance, and Constructors Explained
  2. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
  3. Creating ZIP Archives in Python: From Full Directory to Custom File Selection
  4. Master Python Unit Testing with PyUnit: A Practical Guide & Example
  5. Python List index() – How to Find Element Positions with Practical Examples
  6. Master Python Regular Expressions: re.match(), re.search(), re.findall() – Practical Examples
  7. Python Calendar Module: Expert Guide with Code Examples
  8. Master Python Multithreading: GIL Explained with Practical Examples
  9. Master Python Attrs: Build Advanced Data Classes with Practical Examples
  10. Master Python Extension Programming with C: Build Fast, Native Modules