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?
- It stores data in an unordered, hash‑table‑like structure, with elements as keys and their counts as values.
- Counting items in any iterable—strings, lists, tuples, or dictionaries—is straightforward.
- Built‑in arithmetic operations (addition, subtraction, intersection, union) allow powerful set‑like manipulations.
- It can aggregate counts from other
Counterinstances seamlessly.
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
- elements() – Returns an iterator over elements with positive counts.
- most_common([n]) – Returns the n most common elements as a list of (elem, count) tuples.
- subtract(other) – Subtracts counts from another Counter.
- update(other) – Adds counts from another Counter.
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
- Counter is a dictionary subclass that counts elements in any iterable.
- It supports efficient counting, arithmetic operations, and a suite of utility methods.
- Common use‑cases include frequency analysis, histogram generation, and data aggregation.
- For full documentation, see the Python Counter docs.
Python
- Python OOP Fundamentals: Classes, Objects, Inheritance, and Constructors Explained
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
- Creating ZIP Archives in Python: From Full Directory to Custom File Selection
- Master Python Unit Testing with PyUnit: A Practical Guide & Example
- Python List index() – How to Find Element Positions with Practical Examples
- Master Python Regular Expressions: re.match(), re.search(), re.findall() – Practical Examples
- Python Calendar Module: Expert Guide with Code Examples
- Master Python Multithreading: GIL Explained with Practical Examples
- Master Python Attrs: Build Advanced Data Classes with Practical Examples
- Master Python Extension Programming with C: Build Fast, Native Modules