Introduction π
The collections module provides high-performance, feature-rich alternatives to Pythonβs built-in data types. These specialized container datatypes improve readability, efficiency, and functionality for real-world applications.
Note
1. namedtuple β Lightweight Object Replacement π§±
namedtuple creates tuples with named fields. It behaves like a class but is immutable and lightweight.
namedtuple_example.py
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)
print(p)- β Access by name (p.x)
- β Memory efficient
- β Immutable like normal tuples
2. deque β Fast Queue/Stack Implementation π
deque is ideal for append/pop operations from both ends. Faster than lists for queue/stack usage.
deque_example.py
from collections import deque
dq = deque([1, 2, 3])
dq.append(4)
dq.appendleft(0)
print(dq)
dq.pop()
dq.popleft()
print(dq)- β append() & appendleft()
- β pop() & popleft()
- β Efficient O(1) operations
3. Counter β Count Items Easily π’
Counter counts the occurrence of elements in an iterable.
counter_example.py
from collections import Counter
counts = Counter("banana")
print(counts)
print(counts["a"])
print(counts.most_common(2))- β Frequency counting
- β Analyze text, logs, inventory
- β Supports arithmetic operations between counters
4. defaultdict β Default Values for Missing Keys π
defaultdict automatically assigns a default value when a missing key is accessed.
defaultdict_example.py
from collections import defaultdict
dd = defaultdict(int)
dd["a"] += 1
dd_list = defaultdict(list)
dd_list["users"].append("Sathish")
print(dd)
print(dd_list)- β Avoids KeyError
- β Perfect for grouping, counting
5. OrderedDict β Keeps Insertion Order π
Python 3.7+ dictionaries preserve insertion order by default, but OrderedDict offers extra methods like move_to_end().
ordereddict_example.py
from collections import OrderedDict
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
od.move_to_end("b")
print(od)- β Useful for LRU caches
- β Provides reordering features
6. ChainMap β Combine Multiple Dictionaries π
ChainMap groups multiple dictionaries into a single view.
chainmap_example.py
from collections import ChainMap
defaults = {"theme": "dark", "language": "en"}
user_settings = {"language": "ta"}
config = ChainMap(user_settings, defaults)
print(config["theme"])
print(config["language"])- β Dictionary layering
- β Useful for configuration files
7. UserDict, UserList, UserString β Custom Mutable Classes π οΈ
These classes allow you to create custom versions of built-in types with extended behaviors.
userdata_example.py
from collections import UserDict
class MyDict(UserDict):
def popitem(self):
print("Pop called")
return super().popitem()
d = MyDict({"a": 1, "b": 2})
d.popitem()- β Extend dict, list, or string safely
- β Useful for validation, custom behavior
8. Complete Real-World Example β Word Frequency Counter π
word_frequency.py
from collections import Counter
text = "apple banana apple orange banana apple"
words = text.split()
freq = Counter(words)
print(freq)
print(freq.most_common(1))β Best for text analysis & NLP tasks
9. Real-World Example β Queue System Using deque π
queue_example.py
from collections import deque
queue = deque()
queue.append("User1")
queue.append("User2")
queue.append("User3")
print("Serving:", queue.popleft())
print("Now:", queue)10. Collections Module Cheat Sheet π
| Class | Description |
|---|---|
| namedtuple | Lightweight object alternative |
| deque | Fast queue/stack |
| Counter | Counts elements |
| defaultdict | Default values for missing keys |
| OrderedDict | Ordered dictionary with extra features |
| ChainMap | Combine dictionaries |
| UserDict | Custom dictionary behavior |
| UserList | Custom list behavior |
| UserString | Custom string behavior |
Best Practices π‘
- β Use Counter for counting frequencies
- β Use deque instead of list for queues
- β Use defaultdict when grouping items
- β Use namedtuple for clean, immutable objects
- β Use ChainMap for layered configurations
Conclusion π
You now fully understand the Collections Module! Want the next topic? Try itertools, functools, statistics, or pathlib. Just tell me! π