The collections Module
Purpose-built containers that make everyday counting, grouping and queueing trivial
dict and list handle almost everything, but three specialised containers from the standard-library collections module remove boilerplate you would otherwise write by hand every day. Counter tallies things, defaultdict supplies a value for missing keys automatically, and deque adds and removes from both ends in constant time. None of them is exotic; each is just the plain data structure you already know with the tedious parts done for you.
- tally items with
Counterand read the most common ones, - group and accumulate values with
defaultdictwithoutKeyError, - build fast queues and stacks with
deque, - explain why
deque.popleft()beatslist.pop(0), - pick the right container for a given task.
1. Why reach past plain dict and list?
You already build dictionaries and lists comfortably. But some patterns keep repeating: counting how many times each value appears, collecting items into groups keyed by some property, or treating a list as a queue where you remove from the front. Each of these has a clean solution in raw Python, and each also has an annoying wrinkle.
Counting by hand means checking whether a key exists before you increment it:
counts = {}
for word in words:
if word not in counts:
counts[word] = 0
counts[word] += 1
Grouping by hand has the same shape — you must create the empty list the first time you see a key. And using a plain list as a queue is quietly slow: list.pop(0) shifts every remaining element one slot to the left, so removing from the front of an n-element list costs O(n) each time.
The collections module ships three containers that erase exactly these wrinkles. You import them once and the boilerplate disappears:
from collections import Counter, defaultdict, deque