Lesson · Useful Standard Library Collections
collections
55 min readcollections
`collections` adds specialized containers such as `Counter`, `defaultdict`, `deque`, and `ChainMap`. Choosing one can replace custom bookkeeping with a well-tested abstraction.
Learning goals
- Count a sequence with
Counterand read the result as a mapping of item to frequency. - Group items with
defaultdict(list)and point to the line that creates each new list. - Add and remove at both ends of a
dequeand explain why it beats a list for queue work. - Check membership in a
defaultdictwithout triggering the factory. - Pick between
Counter,defaultdict,deque, andChainMapfor a stated workload.
Mental model
The containers in this module are answers to specific workload shapes: frequency counting, grouping with automatic initialization, work at both ends of a sequence, and layered lookup. Each one wraps a plain dictionary or list and removes bookkeeping a developer would otherwise write by hand. The skill is recognizing the shape before writing the loop.
Core idea
collections specializes the two workhorse structures: Counter and defaultdict are dictionaries with a tuned default behavior, deque is a list optimized at both ends, and ChainMap is a lookup that walks several mappings in order. Choosing the right container deletes code instead of adding it, because the missing-key or append-left logic already lives inside.
Counter
Counter is a dictionary subclass for frequency counts and multisets. Its arithmetic operations are useful when counts themselves are part of the domain.
defaultdict
defaultdict calls a factory when a missing key is accessed through __getitem__. It removes repetitive initialization logic but can also create entries as a side effect of access.
deque
deque provides efficient append and pop operations at both ends. It is preferable to a list for queues that repeatedly remove from the left.
ChainMap
ChainMap groups several mappings into one lookup order without copying them: reads search the first mapping, then the next. Writes go to the first mapping only, which suits layered configuration such as defaults, then a user file, then command-line overrides.
namedtuple
namedtuple builds a tuple subclass whose fields have names: Point = namedtuple("Point", ["x", "y"]) gives you Point(1, 2).x while keeping tuple behavior. Instances are immutable and still satisfy isinstance checks against tuple.
Walkthrough
Counter("banana")walks the string and tallies letters, so the mapping ends up with'a': 3and'n': 2; each letter is counted on the fly, with no loop variable to manage.groups[word[0]].append(word)does two things per word:defaultdictinserts[]the first time a letter appears, thenappendadds the word. Nosetdefaultcall or membership test appears in the source.queue.appendleft(0)adds at the front in constant time, so the deque prints asdeque([0, 1, 2, 3]).- Predict before running: the three printed lines, including which letter is most frequent in
"banana".
Experiments to try
- Call
counts.most_common(1); then evaluatecounts + Counter("bandana")and read how the counts combine. - Replace
defaultdict(list)with a plain dictionary plussetdefault(key, []); compare the two loops and name what the factory removed. - Call
appendleftandpoplefton the deque, thenappendandpop; record which end each call touched. - Read a missing key with
"c" in groupsand then withgroups["c"]; inspectgroupsafterwards and explain the difference.
Common mistakes
- Using
groups[key]to test for a key in adefaultdict; the lookup runs the factory and inserts an empty container, silently changing the data. - Treating a
Counterlookup as a normal dictionary lookup:counts["z"]returns0instead of raising, which can hide a mistyped key. - Using a list as a queue:
pop(0)shifts every remaining element, so a long-lived queue degrades;deque.popleft()is the constant-time equivalent. - Forgetting that a
ChainMapwrite lands only in the first mapping: later reads still prefer the first mapping, and the underlying mappings do not change.
Practice: Easy
- Run the worked example, then print
counts.most_common()and state which letter is most frequent and where'b'lands in the order. - Rebuild
groupswith a plaindictandgroups.setdefault(word[0], []).append(word); compare the two loops and name the bookkeeping the factory removed. - Take
deque([1, 2, 3])and performappendleft(0),pop(), andpopleft()in that order; print the deque after each call and name the end each method touched.
Practice: Medium
- Subtract a
Counter("nan")from aCounter("banana")and explain which counts survive and why zero results disappear from the subtraction. - Build a
ChainMapover a defaults dict and an overrides dict; set a key through theChainMapand show that the write lands in the first mapping even when the key exists only in the second, with the first mapping shadowing later reads. - Run 100,000 append-then-remove-left cycles on both a
dequeand alist(withpop(0)) and time each loop withtime.perf_counter(); report which container wins and why.
Practice: Hard
- Design a small inventory report:
namedtuplerows, adefaultdict(list)index by category, and aCounterfor category totals; define the sample data, the expected output, and one invariant you can assert before writing code. - Failure lab: trigger three behaviors on purpose, a
defaultdictread that inserts an empty list, aCounterlookup for a missing letter returning0, and aChainMapwrite that a later read shadows; explain the mechanism behind each. - Connect this lesson to the performance module: time
Counter(text)against a hand-written loop over the same string and explain what the specialized container does differently.
Lesson checklist
- I can pick between
Counter,defaultdict,deque, andChainMapfor a stated workload. - I can explain why a
defaultdictlookup creates an entry and how to test for a key safely. - I can say what each end operation on a
dequecosts and whylist.pop(0)degrades on long queues. - I can trace where a
ChainMapwrite lands and how reads resolve across the mappings.
Remember
`collections` replaces hand-written bookkeeping with tuned containers: `Counter` for tallies, `defaultdict` for automatic initialization, `deque` for work at both ends of a sequence, and `ChainMap` for layered lookup, with `namedtuple` giving tuple records named fields. Match the container to the shape of the workload and the code you would otherwise write by hand disappears.
Interview angles
What is the main purpose of **Counter**?+
Counter is a dictionary subclass for frequency counts and multisets. Its arithmetic operations are useful when counts themselves are part of the domain.
What should you pay attention to when using **defaultdict**?+
defaultdict calls a factory when a missing key is accessed through __getitem__. It removes repetitive initialization logic but can also create entries as a side effect of access.
How does **deque** fit into this lesson?+
deque provides efficient append and pop operations at both ends. It is preferable to a list for queues that repeatedly remove from the left.
Why can reading `groups["c"]` change a `defaultdict` even though you only wanted to test for a key?+
defaultdict.__getitem__ calls the factory when the key is missing and stores the result, so the read inserts [] into the mapping. Use "c" in groups or groups.get("c") when the lookup must not create entries.