Introduction to Python’s collections Module
Introduction
Python’s built-in data types — list, tuple, set, and dict — are powerful.
But sometimes, you need more flexible and efficient data structures for real-world programming.
That’s where Python’s collections module comes in.
It provides specialized container datatypes that make data handling easier, faster, and cleaner.
In this post, you’ll learn the most useful ones with examples.
1. Counter
Counter is a dictionary subclass for counting hashable objects.
Example:
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count = Counter(data)
print(count)
Output:
Counter({'apple': 3, 'banana': 2, 'orange': 1})
You can also use count.most_common(1) to find the most frequent element.
2. defaultdict
A normal dictionary raises a KeyError when you access a missing key.
defaultdict automatically assigns a default value for missing keys.
Example:
from collections import defaultdict
scores = defaultdict(int)
scores['Alice'] += 10
scores['Bob'] += 5
print(scores)
Output:
defaultdict(<class 'int'>, {'Alice': 10, 'Bob': 5})
Useful in counting, grouping, and accumulating data without worrying about missing keys.
3. namedtuple
Ever wished you could access tuple elements with names instead of indexes?
namedtuple makes that possible!
Example:
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'grade'])
s1 = Student('Ravi', 20, 'A')
print(s1.name, s1.age, s1.grade)
Output:
Ravi 20 A
Acts like both a tuple and an object — lightweight and readable.
4. deque (Double-Ended Queue)
deque is like a list, but you can efficiently add/remove items from both ends.
Example:
from collections import deque
dq = deque(['a', 'b', 'c'])
dq.append('d') # add to right
dq.appendleft('z') # add to left
print(dq)
dq.pop()
dq.popleft()
print(dq)
Output:
deque(['z', 'a', 'b', 'c', 'd'])
deque(['a', 'b', 'c'])
Great for implementing queues, stacks, or sliding-window algorithms.
5. ChainMap
ChainMap combines multiple dictionaries into one view.
Example:
from collections import ChainMap
defaults = {'theme': 'light', 'showLineNumbers': True}
user_settings = {'theme': 'dark'}
settings = ChainMap(user_settings, defaults)
print(settings['theme'])
Output:
dark
Useful when managing layered configurations (like app settings).
Why we require collections Module?
-
More efficient for certain operations
-
Cleaner syntax and readability
-
Reduces boilerplate code
-
Great for data analysis, parsing, and simulations
Quick Challenge
Write a program using Counter to count the number of characters in a given string and display the top 3 most common characters.
Conclusion
The collections module is a hidden gem in Python’s standard library.
It provides optimized, ready-to-use tools for data manipulation — a must-learn for every Python programmer.
.png)
Comments
Post a Comment