▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
collections and itertools
Counter, defaultdict, deque and the itertools toolkit.
🎬 Video version coming soon — read it now
Two standard-library modules solve many everyday problems in a line or two. Knowing them separates intermediate Python from advanced.
Counter: counting made easy
That replaces the counts.get(w, 0) + 1 loop you wrote by hand in Lists, Dicts & Data.
defaultdict: no more "if key not in dict"
A missing key is created automatically using the factory you gave (list, int, set...).
deque: a fast queue
namedtuple: lightweight records
(For most new code, a frozen dataclass is clearer.)
itertools: building blocks for loops
groupby: group sorted data
groupby only groups neighbouring items, so sort by the same key first. Forgetting that is a classic bug.
Also worth knowing
collections.ChainMap: look up keys across several dictionaries, such as settings with defaultsitertools.batched(Python 3.12+): split an iterable into chunks of n, which is handy for sending items to an API in batches
In one line
Counter counts, defaultdict groups, deque queues, and itertools chains, slices, combines and groups, all built in.
Share with a friend