Sub topic 1
Why the collections module exists
Prerequisites
This chapter assumes you can:
- Write basic Python: loops, conditionals, and functions.
- Use
dictandlist, including key lookup, assigning to a key, andappend. - Explain what makes an object hashable. For example, you know why a
listcannot be adictkey but atupleof strings can. - Import names from the standard library with
importandfrom ... import ....
You do not need to know anything about Counter, defaultdict, or deque yet. This chapter introduces the problems they solve and shows each one briefly. Later chapters cover each type in depth.
What you will learn
By the end of this chapter you should be able to:
- Say what the
collectionsmodule is and which three of its containers this tutorial covers. - Recognize three recurring code patterns (counting, grouping, queueing) that plain
dictandlisthandle awkwardly. - Explain how
Counter,defaultdict, anddequerelate todictandlist. - Avoid a common naming mistake that breaks imports from the module.
The built-ins are general on purpose
Python's built-in containers are list, dict, set, and tuple. They are general tools. A dict maps any hashable key to any value, and a list holds an ordered sequence. Because they are so general, a handful of everyday jobs take more code than they should, or perform worse than they should.
The collections module is part of the standard library. It adds specialized containers that fit those jobs. Each container is a small, focused tool. None of them replaces dict or list, and you pick one when its behavior matches your task.
The module contains several containers. This tutorial covers three of them:
| Container | Solves | Closest built-in |
|---|---|---|
| `Counter` | Counting how often each hashable item occurs | `dict` of item to integer |
| `defaultdict` | Building a dict without checking whether a key exists | `dict` |
| `deque` | Adding and removing items at both ends efficiently | `list` |
The module also has namedtuple, OrderedDict, ChainMap, UserDict, UserList, and UserString. They are useful, but this tutorial does not cover them.
You import what you need by name:
from collections import Counter, defaultdict, dequeThree recurring problems
The best way to see why the module exists is to write the awkward version first. Each of the next three sections shows a task, the plain-Python solution, and the collections solution.
Problem 1: counting
Suppose you want to know how many times each word appears in a list. With a plain dict, a first attempt often looks like this:
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)
# {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}This works. The if is needed because counts[word] += 1 raises KeyError the first time a word appears. You can shorten it with dict.get, which takes a fallback value:
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
# {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}Now the same job with Counter:
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
print(counts["dog"]) # 0, and 'dog' is not added to countsCounter takes the whole iterable and does the loop for you. It also gives you most_common, which a plain dict would need a sorted call and a key function to imitate. A missing item reads as 0 instead of raising KeyError, and reading it does not add it to the counter.
Problem 2: grouping
Now suppose you want to group words by their first letter, so each letter maps to a list of words. A plain dict needs a check, because by_letter[letter].append(word) fails when the key is missing:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for word in words:
letter = word[0]
if letter not in by_letter:
by_letter[letter] = []
by_letter[letter].append(word)
print(by_letter)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Some programmers use dict.setdefault to compress the check into one line:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for word in words:
by_letter.setdefault(word[0], []).append(word)
print(by_letter)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}This is correct, but it has a cost. Python evaluates the argument [] on every call, so it builds a new empty list for every word, then throws it away whenever the key already exists. It also reads less clearly than the loop above.
defaultdict moves the "what to do for a missing key" decision into the constructor:
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(dict(by_letter))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}The argument list is a callable that takes no arguments. The first time you read a missing key, the defaultdict calls list() and stores the empty list under that key. The loop body is now a single line with no existence check.
Problem 3: queues
A queue processes items in the order they arrived: first in, first out. A list is the obvious container. You add to the end with append and take from the front with pop(0):
queue = [1, 2, 3]
queue.append(4)
first = queue.pop(0)
print(first) # 1
print(queue) # [2, 3, 4]The code is correct, but pop(0) is slow on large lists. A list stores its items in one contiguous block of memory. Removing the first item means every remaining item must shift one position left, so the cost grows with the length of the list. deque (pronounced "deck", short for double-ended queue) is built for this:
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
first = queue.popleft()
print(first) # 1
print(queue) # deque([2, 3, 4])Removing from the left end of a deque does not shift the other items, so it takes about the same time no matter how long the queue is.
You can see the difference yourself. This script drains 100,000 items from each container, one at a time, from the front:
from collections import deque
from timeit import timeit
N = 100_000
def drain_list():
items = list(range(N))
while items:
items.pop(0)
def drain_deque():
items = deque(range(N))
while items:
items.popleft()
print("list.pop(0): ", round(timeit(drain_list, number=1), 3), "seconds")
print("deque.popleft: ", round(timeit(drain_deque, number=1), 3), "seconds")The exact numbers depend on your machine and Python version, so none are shown here. On most machines the list version is clearly slower, and the gap widens as N grows. The deque trade-offs get their own chapter, including the cases where a list is the better choice.
How the three containers relate to dict and list
Two of the three containers are dict subclasses. The third is not related to list by inheritance. You can check this directly:
from collections import Counter, defaultdict, deque
print(issubclass(Counter, dict)) # True
print(issubclass(defaultdict, dict)) # True
print(issubclass(deque, list)) # False
print(issubclass(deque, dict)) # FalseThis has practical consequences:
- A
Counteris adict. Everything you know about dictionaries still applies:keys(),items(), iteration,in, andlen. Keys must be hashable, exactly as for adict. - A
defaultdictis also adict. It differs in one behavior: what happens when you index a key that is not there. That behavior has surprises, and a later chapter ondefault_factorycovers them. - A
dequeis its own type. It supports indexing,len, iteration, andin, but it does not support slicing, and it is not a drop-in replacement for alist. Indexing into the middle of adequeis slower than for alist.
The following diagram shows the relationships.
A quick map from task to tool
When you meet a task, ask what shape of data it produces and what operation you repeat most often. The following flowchart is a first-pass guide. The final chapter of this tutorial builds a fuller decision process with edge cases.
The last branch matters. If none of the three jobs applies, a plain dict or list is the right choice. The specialized containers are tools for specific jobs.
Why not just write helper code?
You could write your own counting loop or grouping helper, and many programmers have. The standard containers have several advantages.
- Shared vocabulary. Another reader who sees
Counterordefaultdict(list)knows the intent immediately. A hand-written loop makes them read it to find out. - Fewer places for bugs. The existence check in the plain-
dictexamples above is easy to forget or invert. The specialized containers remove that step. - Tested and optimized.
Counteranddequehave fast implementations in the CPython interpreter, written in C. A Python-level helper usually cannot match their speed. - Extra operations.
Countergives youmost_commonand arithmetic between counters.dequegives youmaxlenandrotate. Writing those yourself is more work than learning the container.
Common pitfalls at the start
Naming your own file collections.py
Python searches for modules in the directory of the running script before it searches the standard library. If you save a file called collections.py in your project, then from collections import Counter may import your file instead of the standard library module. You will typically see an error such as ImportError: cannot import name 'Counter'. The same applies to a folder named collections. Pick a different file name.
Confusing collections with collections.abc
The module collections.abc is a separate module inside the package. It holds abstract base classes such as Mapping, Sequence, and Iterable, which you use for type checks like isinstance(x, Mapping). It does not contain Counter, defaultdict, or deque. In old code you may see from collections import Mapping. That import stopped working in Python 3.10, so use collections.abc for those names.
Treating the specialized containers as general upgrades
It is tempting to replace every dict with a defaultdict "just in case". That has a real cost. A defaultdict creates and stores a value whenever you index a missing key, so a typo in a key name silently adds a new entry instead of raising KeyError. A plain dict would have told you about the mistake. Use the specialized container when its default behavior is the behavior you want.
Where the rest of the tutorial goes
The remaining chapters take the three containers one at a time, in this order:
Counter: creating counts, thenmost_common,update,subtract,elements, and arithmetic between counters.defaultdict: grouping and accumulating, then howdefault_factoryworks, when a lookup inserts a key, and the__missing__hook.deque: queue and stack operations, thenmaxlenandrotate, and the performance trade-offs againstlist.- A closing chapter on choosing between
dict,Counter,defaultdict,list, anddequefor a given task.
Each chapter keeps the same habit you should adopt now: write down what the data looks like and which operation repeats most often, then pick the container that makes that operation short and obvious.
Summary
- The
collectionsmodule offers specialized containers for jobs where plaindictandlisttake extra code or run slowly. Countercounts hashable items.defaultdictremoves missing-key checks when you build a dict.dequeadds and removes quickly at both ends.Counteranddefaultdictare subclasses ofdict.dequeis not a subclass oflistand has different strengths.- Plain
dictandliststay the right choice when none of these jobs applies. - Do not name your own file
collections.py.
Exercise
The loop below groups numbers by whether they are even or odd. Rewrite it with defaultdict so the if check is not needed, and say what dict(groups) prints.
nums = [1, 2, 3, 4, 5]
groups = {}
for n in nums:
key = "even" if n % 2 == 0 else "odd"
if key not in groups:
groups[key] = []
groups[key].append(n)
Show answer
Use defaultdict(list): from collections import defaultdict nums = [1, 2, 3, 4, 5] groups = defaultdict(list) for n in nums: key = "even" if n % 2 == 0 else "odd" groups[key].append(n) print(dict(groups)) It prints {'odd': [1, 3, 5], 'even': [2, 4]}. The key 'odd' appears first because 1 is the first number processed and dicts keep insertion order. The first read of each missing key calls list() and stores the empty list, so append always has a list to work on.
Exercise
A program stores pending jobs in a list and always takes the next job with jobs.pop(0). Which collections container fits better, which method replaces pop(0), and why does the change matter more as the list grows? Also, is the replacement container a subclass of list?
Show answer
Use deque. The method popleft() replaces pop(0). A list stores items in one contiguous block, so pop(0) shifts every remaining item one position left, and the cost grows with the length of the list. A deque removes from its left end without shifting the other items, so the cost stays roughly constant. A deque is not a subclass of list, so code that relies on list-only features such as slicing needs adjusting.
Exercise
You save a script named collections.py and add from collections import Counter to it. What problem can this cause, and how do you fix it?
Show answer
Python looks in the script's own directory before the standard library, so the import can pick up your file instead of the standard library module. This often fails with an error such as ImportError: cannot import name 'Counter'. The fix is to rename your file to something else and remove the stale _pycache_ folder beside it.