Python Advanced
Python collections Module
The collections module extends Python's basic data structures with specialized, high-performance alternatives like Counter, defaultdict, namedtuple, and deque.
Counter — Counting Items
Counter builds a dictionary-like object that counts how many times each item appears in a list or string, saving you from writing a manual counting loop.
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
print(counts)
print(counts.most_common(2))defaultdict — Dictionaries with Defaults
A normal dictionary raises a KeyError when you access a missing key. defaultdict automatically creates a default value (like an empty list) for any new key, which is great for grouping data.
from collections import defaultdict
groups = defaultdict(list)
groups["fruits"].append("apple")
groups["fruits"].append("banana")
groups["veggies"].append("carrot")
print(dict(groups))namedtuple — Readable Tuples
namedtuple creates a lightweight class-like tuple where you access fields by name instead of position, making code that returns structured data much easier to read.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)deque — Fast Double-Ended Queue
A regular list is slow when adding or removing items from the front. deque (pronounced "deck") is optimized for fast additions and removals from both ends, ideal for queues and sliding-window problems.
from collections import deque
queue = deque([1, 2, 3])
queue.appendleft(0)
queue.append(4)
print(queue)
queue.popleft()
print(queue)OrderedDict — Insertion-Ordered Dictionaries
Since Python 3.7, regular dictionaries already remember insertion order, but OrderedDict still offers extra methods like move_to_end() and is useful when you need to signal ordering intent explicitly.
For most modern code, a plain dict is enough since it preserves order — reach for OrderedDict only when you need its extra reordering methods.
| Type | Use case |
|---|---|
| Counter | Counting occurrences of items |
| defaultdict | Dictionaries with automatic default values |
| namedtuple | Lightweight objects with named fields |
| deque | Fast append/pop from both ends |
| OrderedDict | Dictionary with explicit reordering methods |
