1. Pythonic Data Structures & Comprehensions
The collections Module: Counter, defaultdict, deque & NamedTuple
Stop reinventing frequency counters, nested grouping dicts, and fixed-size queues—use Python's built-in collections and typing.NamedTuple power tools.
- Count frequencies and top-N items in one line with collections.Counter
- Group items cleanly without KeyError boilerplate using defaultdict
- Use deque for fast O(1) left/right queues and sliding windows, and NamedTuple for lightweight records
Many beginners write 10 lines of if key not in counts: counts[key] = 0 every time they count words or group records. Python's standard-library collections module (plus typing.NamedTuple) gives you battle-tested, C-optimized containers built for these exact tasks.
Why It Matters: Before vs After
Compare manually initializing dictionary keys vs letting Counter and defaultdict handle missing keys automatically:
# Before: manual KeyError guards everywhere
counts = {}
for event in events:
if event not in counts:
counts[event] = 0
counts[event] += 1
# After: expressive, bug-free standard library tools
from collections import Counter
counts = Counter(events)Not only is the second version shorter, it also gives you .most_common(n), safe 0 defaults, and arithmetic merging (+, -) out of the box.
Counter
{'login': 3, 'view': 2} · missing key → 0
defaultdict(list)
Auto-creates [] via __missing__ on first append
deque(maxlen=3)
O(1) popleft/append · fixed sliding window
NamedTuple
Immutable, named fields, still unpackable
Choose the right specialized container to eliminate KeyError boilerplate and O(n) queue bottlenecks.
1. Counting Anything with Counter
Counter is a dict subclass built specifically for tallying frequencies:
from collections import Counter
events = ["login", "view", "login", "purchase", "view", "login"]
counts = Counter(events)
print(counts) # Counter({'login': 3, 'view': 2, 'purchase': 1})
print(counts["logout"]) # 0 (no KeyError on missing keys!)
print(counts.most_common(2)) # [('login', 3), ('view', 2)]Notice two huge wins:
- Accessing a missing key returns
0instead of crashing withKeyError(and doesn't insert0into the dictionary!). - You can combine tallies across batches with
today_counts + yesterday_counts, or subtract withstock - sold.
2. Grouping Without Boilerplate Using defaultdict
Suppose you want to group students by their track:
from collections import defaultdict
groups = defaultdict(list)
enrollments = [("Backend", "Maya"), ("Data", "Liam"), ("Backend", "Sam")]
for track, student in enrollments:
groups[track].append(student)
print(dict(groups))
# {'Backend': ['Maya', 'Sam'], 'Data': ['Liam']}Mental Model: How defaultdict Works Under the Hood
When you access groups[track]:
- If
trackexists ingroups, Python returns its value normally. - If
trackis missing,defaultdictruns its internal__missing__(key)hook, calls the factory function you passed (e.g.,list()→[]), stores that new empty list undergroups[track], and returns it—all before.append(student)executes!
You pass the callable factory itself (list, set, int, or lambda: ...)—without calling ()—so defaultdict creates a fresh container for each new key.
Because reading groups["missing"] on a defaultdict silently inserts an empty key, convert finished results with dict(groups) before returning them from a function or serializing to JSON!
3. Fast Queues & Sliding Windows with deque
Regular Python list objects store elements in a contiguous array in memory. Adding/removing at the right end (.append(), .pop()) is O(1), but .insert(0, x) and .pop(0) at the left end are O(n) because every remaining element has to shift one slot!
collections.deque (double-ended queue) uses a doubly-linked list of fixed blocks, giving O(1) operations on both ends—and supports maxlen for automatic sliding windows:
from collections import deque
# Keep only the 3 most recent log messages automatically
recent_logs = deque(maxlen=3)
for msg in ["boot", "db_connect", "auth_ok", "request_200"]:
recent_logs.append(msg)
print(list(recent_logs)) # ['db_connect', 'auth_ok', 'request_200']
# Fast FIFO queue operations
queue = deque(["task1", "task2"])
queue.append("task3")
next_task = queue.popleft() # 'task1' in O(1) time4. Readable Lightweight Records with NamedTuple
When returning 3 or 4 values from a function, plain tuples like (200, "OK", 14.2) force callers to remember magic indexes (res[0], res[2]). typing.NamedTuple keeps tuple speed and immutability while giving every field a name and type hint:
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
label: str = "origin"
p = Point(3.0, 4.0, "target")
print(p.x, p.y, p.label) # 3.0 4.0 target
x, y, _ = p # Still supports tuple unpacking!Decision Table: Choosing the Right Container
| Need | Best Tool | Why Not Plain list / dict? |
|---|---|---|
| Count frequencies & top-K items | Counter | Avoids manual dict.get(k, 0) + 1; adds .most_common() |
| Group items into lists or sets | defaultdict(list) / defaultdict(set) | Cleaner than repeated dict.setdefault(k, []) allocations |
| FIFO queue or last-N sliding window | deque(maxlen=N) | list.pop(0) is O(n) slow; deque.popleft() is O(1) |
| Small, immutable typed record | NamedTuple | Self-documenting fields + hashable + tuple unpacking |
| Rich mutable/validated domain object | @dataclass (Module 3) | Supports defaults, methods, and optional mutability |
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Use Counter to find the 3 most common words in text = "python is clean python is fast and python is fun" (after splitting on spaces).
Quick Checkpoints
What happens if you access c['missing'] on a Counter()?
Why should you pass list (not list()) to defaultdict(list)?