Sub topic 1
Why the collections module exists
Python's built-in dict and list handle most jobs. Some jobs come up so often that writing them by hand with those two types gets repetitive or slow. The collections module is a standard-library module that packages those jobs as ready-made container types. This chapter shows the problems they solve and introduces the three this tutorial covers: Counter, defaultdict, and deque.
Prerequisites
This chapter assumes you already know:
- Basic Python syntax, loops, and functions.
- How to use
dictandlist, including key lookup andappend. - The difference between hashable and unhashable objects. For example, a list cannot be a dict key.
- How to import names from the standard library.
The problem: boilerplate around plain containers
Counting how often each word appears is one of the most common small tasks in Python. With a plain dict, you must handle the first time you see each word separately:
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}The code works. But the if/else exists only because a missing key raises KeyError. Every program that counts, groups, or accumulates repeats this pattern.
A second kind of problem is speed. A list is fast at adding and removing items at its end. Removing from the front with pop(0) is slow, because Python must shift every remaining item one place. If you use a list as a queue, the cost grows with the queue's length.
The collections module addresses both problems with types that give you the behavior directly.
What the module provides
collections holds several specialized containers. This tutorial covers three of them:
| Type | Problem it solves | Behaves like |
|---|---|---|
| `Counter` | Counting hashable items | A `dict` that maps items to integer counts |
| `defaultdict` | Grouping or accumulating without checking for missing keys | A `dict` that creates a value for a missing key |
| `deque` | Fast adds and removes at both ends | A `list` optimized for the front and the back |
Counter and defaultdict are subclasses of dict. Everything you know about dicts still works on them: indexing, in, keys(), items(), and iteration. deque is a separate type, closer to a list.
The module also contains namedtuple, OrderedDict, ChainMap, and others. They are outside this tutorial's scope.
The same task with Counter
Here is the word count again. Counter takes any iterable and tallies its items:
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts) # Counter({'the': 3, 'and': 2, 'cat': 1, 'hat': 1, 'bat': 1})
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
print(counts["dog"]) # 0The loop and the if/else are gone. Two details are worth noticing:
most_common(2)returns the two highest counts first.- A missing item such as
"dog"reads as0instead of raisingKeyError. Reading it does not add"dog"to the counter.
The next chapters cover Counter in detail.
How the three containers relate
The three types do different jobs, but they share a pattern. Each one takes a common hand-written idiom and gives it a name and a tested implementation.
Because the types are built for specific jobs, picking one also tells readers what your code is doing. Counter(words) states the intent in one line. The final chapter of this tutorial gives a method for choosing between these types and plain dict and list.
Importing from collections
You can import the module or import individual names:
import collections
from collections import Counter, defaultdict, deque
a = collections.Counter("hello")
b = Counter("hello")
print(a == b) # TrueBoth forms give you the same class. The from form is more common because it keeps call sites short.
Note the capitalization. Counter is capitalized, while defaultdict and deque are all lowercase. Getting this wrong gives an ImportError.
Common errors at this stage
Three mistakes show up often when people first use the module.
- Naming your own file
collections.py. Python searches the script's directory before the standard library, so your file can hide the real module. The import then fails or loads your code instead. - Counting unhashable items.
Counteruses items as dict keys, so they must be hashable. This fails:
from collections import Counter
try:
Counter([[1, 2], [3, 4]])
except TypeError as error:
print(error) # unhashable type: 'list'Convert each inner list to a tuple first, for example Counter(tuple(x) for x in data).
- Assuming a special container is always better. A plain
dictorlistis the right choice when you don't need the extra behavior. AddingCounterto code that never counts only adds confusion.
What comes next
The following chapters take each container in turn. Counter comes first, then defaultdict, then deque. The last chapter compares them with dict and list so you can choose the right one for a task.
Exercise
A teammate counts the items in a list with a loop and an if/else on a plain dict. Name the specialized type from collections that removes that boilerplate, and explain what happens when you read a count for an item that was never in the list.
Show answer
Use Counter. It tallies the items of any iterable of hashable values. Reading a missing item returns 0, and the item is not added to the counter, so no KeyError is raised.
Exercise
You save a script as collections.py and it contains "from collections import Counter". Why does the import fail, and what do you do?
Show answer
Python searches the script's own directory before the standard library, so "collections" resolves to your file instead of the real module. Rename the file (and remove its _pycache_ entry) so the standard-library module is found.