The collections Module: Python's Supercharged Data Structures
Counter, defaultdict, deque, namedtuple — four ready-made containers that turn ten lines of fiddly dictionary code into one.After this lesson, you will be able to:
- Use Counter to count items (anything that can be a dict key) and add or subtract frequency tables
- Use defaultdict to eliminate 'key not found' boilerplate in grouping patterns
- Use namedtuple to create lightweight, readable, immutable records
- Use deque for O(1) append and pop from both ends — including sliding windows
- Use bisect for O(log n) search and insertion in sorted lists
Before you start
#Why the collections Module Exists
list, dict, and set are excellent general-purpose containers. But for some jobs they make you write the same repetitive code again and again. The collections module provides special containers that remove that repetition and often run faster.# The full import (pick what you need)
from collections import (
Counter, # counting hashable objects
defaultdict, # dict with auto-created missing values
OrderedDict, # dict with order-sensitive operations
namedtuple, # immutable tuple with named fields
deque, # a list that is fast at both ends (say "deck")
ChainMap, # layered dict views
)
import bisect # binary search on sorted lists#Counter: Counting Made Effortless
Counter is a special kind of dict that answers 0 for a missing key. It is built for counting things that can be dict keys, such as strings, numbers and tuples.from collections import Counter
# Count characters in a string
char_count = Counter("banana")
print(char_count)
# Counter({'a': 3, 'n': 2, 'b': 1})
# Count words in a list
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = Counter(words)
print(word_count)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# Count words from a text
text = "to be or not to be that is the question to be"
token_counts = Counter(text.split())
print(token_counts)
# Counter({'to': 3, 'be': 3, 'or': 1, 'not': 1, ...})#.most_common(n)
vocab = Counter("the cat sat on the mat the cat sat".split())
# Top 3 most frequent
print(vocab.most_common(3))
# [('the', 3), ('cat', 2), ('sat', 2)]
# All items, most common first
print(vocab.most_common())
# [('the', 3), ('cat', 2), ('sat', 2), ('on', 1), ('mat', 1)]
# Access a missing key -- returns 0, not KeyError
print(vocab["elephant"]) # 0#Counter Arithmetic
Counter supports set-like arithmetic that makes combining frequency tables elegant.
c1 = Counter({"apple": 5, "banana": 3, "cherry": 1})
c2 = Counter({"banana": 2, "cherry": 4, "date": 6})
# Addition: combine counts
print(c1 + c2)
# Counter({'date': 6, 'apple': 5, 'banana': 5, 'cherry': 5})
# Subtraction: keep only positive results
print(c1 - c2)
# Counter({'apple': 5, 'banana': 1})
# 'cherry' becomes -3, dropped (only positives kept)
# Intersection: minimum of each count
print(c1 & c2)
# Counter({'banana': 2, 'cherry': 1})
# Union: maximum of each count
print(c1 | c2)
# Counter({'date': 6, 'apple': 5, 'cherry': 4, 'banana': 3})#Use Case: Finding the Most Common Words
from collections import Counter
sentences = [
"the cat sat on the mat",
"the dog ran in the park",
"the cat and the dog played",
]
# Count every word across all the sentences
all_words = []
for line in sentences:
all_words.extend(line.split())
word_counter = Counter(all_words)
# The most frequent words are almost always the boring ones
print("Top 5 words:", word_counter.most_common(5))
# Give each common word a number, so you can refer to it by index
how_many = 10
numbered = {word: idx for idx, (word, _) in enumerate(word_counter.most_common(how_many))}
print("Numbered:", numbered)
# {'the': 0, 'cat': 1, 'dog': 2, ...}
# Encode a sentence
def encode(sentence, vocab):
"""Convert words to vocab ids, unknown words get -1."""
return [vocab.get(w, -1) for w in sentence.split()]
print(encode("the cat ran", numbered)) # [0, 1, 6]You have Counter({'a': 3, 'b': 1}) - Counter({'a': 2, 'b': 5}). What is the result?
Counter({'a': 1}). Counter subtraction keeps only positive results and drops zeros and negatives. b becomes 1 - 5 = -4, which is dropped.#defaultdict: Eliminate Missing-Key Boilerplate
defaultdict is a dict that makes a starting value for a missing key instead of raising KeyError. You give it a factory: a function (such as list or int) that makes that starting value.from collections import defaultdict
# Without defaultdict -- classic verbose pattern
groups = {}
words = [("fruit", "apple"), ("veggie", "carrot"), ("fruit", "banana"), ("veggie", "broccoli")]
for category, item in words:
if category not in groups: # extra check, needed every time
groups[category] = [] # extra setup, needed every time
groups[category].append(item)
print(groups)
# {'fruit': ['apple', 'banana'], 'veggie': ['carrot', 'broccoli']}
# With defaultdict(list) -- missing keys auto-get an empty list
groups_v2 = defaultdict(list)
for category, item in words:
groups_v2[category].append(item) # no check needed!
print(dict(groups_v2))
# {'fruit': ['apple', 'banana'], 'veggie': ['carrot', 'broccoli']}#Common Default Factories
# defaultdict(int) -- missing keys default to 0
word_count = defaultdict(int)
text = "the quick brown fox jumps over the lazy dog the fox"
for word in text.split():
word_count[word] += 1 # no .get() or check needed
print(dict(word_count))
# defaultdict(set) -- missing keys default to empty set
# Use case: an index from each word to the documents that contain it
inverted_index = defaultdict(set)
documents = {
"doc1": "python beginner tutorial",
"doc2": "python web development flask",
"doc3": "beginner tutorial for flask",
}
for doc_id, content in documents.items():
for word in content.split():
inverted_index[word].add(doc_id)
# Which docs contain "python"?
print(inverted_index["python"]) # {'doc1', 'doc2'} (set order can vary)
# Which docs contain "machine"? None of them --
# and this lookup just CREATED the key. See the question below.
print(inverted_index["machine"]) # set()
print(len(inverted_index)) # 8 -- "machine" is now stored
# defaultdict with a lambda -- custom defaults
config = defaultdict(lambda: "NOT_SET")
config["debug"] = True
print(config["debug"]) # True
print(config["log_level"]) # "NOT_SET" (auto-created)inverted_index has 7 words in it. You read inverted_index['machine'], a word in none of the documents. What is the dict's length afterwards?
#Grouping with defaultdict(list)
from collections import defaultdict
words = ["apple", "fig", "banana", "kiwi", "plum", "cherry", "pear", "date"]
# Group the words by how long they are
by_length = defaultdict(list)
for word in words:
by_length[len(word)].append(word)
for length in sorted(by_length):
print(length, by_length[length])
# 3 ['fig']
# 4 ['kiwi', 'plum', 'pear', 'date']
# 5 ['apple']
# 6 ['banana', 'cherry']#OrderedDict: Order-Sensitive Operations
OrderedDict?from collections import OrderedDict
# OrderedDict has .move_to_end() which regular dicts lack
od = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
od.move_to_end("a") # move "a" to the end
print(list(od.keys())) # ['b', 'c', 'a']
od.move_to_end("a", last=False) # move "a" to the front
print(list(od.keys())) # ['a', 'b', 'c']
# OrderedDict equality considers order; regular dict equality does not
d1 = OrderedDict([("a", 1), ("b", 2)])
d2 = OrderedDict([("b", 2), ("a", 1)])
print(d1 == d2) # False -- order matters for OrderedDict
r1 = {"a": 1, "b": 2}
r2 = {"b": 2, "a": 1}
print(r1 == r2) # True -- order does NOT matter for regular dict#popitem and the least recently used
from collections import OrderedDict
od = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
od.move_to_end("a") # "a" was just used, so it goes to the back
print(od.popitem(last=False)) # ('b', 2) -- the front is the entry used longest ago
print(list(od)) # ['c', 'a']Moving an entry to the back on every use and dropping from the front when the dict is full is how a least-recently-used (LRU) cache works. The complete cache, built from a linked list and a dict so you can see why each step is O(1), is in the lesson on Linked Lists, Part 2.
`od` holds 'a', 'b', 'c' in that order. You call `od.move_to_end('a')` and then `od.popitem(last=False)`. Which entry comes out?
#namedtuple: Readable, Memory-Efficient Records
namedtuple is a tuple whose positions have names. You read a field by name instead of by index, which makes code clearer, and it takes the same memory as a plain tuple.from collections import namedtuple
# Define a namedtuple type
Point = namedtuple("Point", ["x", "y"])
Color = namedtuple("Color", ["r", "g", "b"])
Employee = namedtuple("Employee", ["name", "department", "salary"])
# Create instances
p = Point(x=3, y=7)
c = Color(255, 128, 0)
emp = Employee("Alice", "Engineering", 95000)
# Named access (much clearer than p[0], p[1])
print(f"Point: ({p.x}, {p.y})")
print(f"Color: rgb({c.r}, {c.g}, {c.b})")
print(f"{emp.name} in {emp.department} earns ${emp.salary:,}")
# Still a tuple -- index access and unpacking work
print(p[0]) # 3
x, y = p # unpacking
print(x, y) # 3, 7
# Immutable -- cannot modify fields
# p.x = 10 # AttributeError: can't set attribute
# _replace() creates a NEW namedtuple with one field changed
p2 = p._replace(x=10)
print(p2) # Point(x=10, y=7)
print(p) # Point(x=3, y=7) -- original unchanged
# _asdict() converts to a regular dict
print(emp._asdict())
# {'name': 'Alice', 'department': 'Engineering', 'salary': 95000}#Memory Comparison: namedtuple vs dict
import sys
# Representing the same data three ways
Point_nt = namedtuple("Point_nt", ["x", "y", "z"])
p_namedtuple = Point_nt(1.0, 2.0, 3.0)
p_tuple = (1.0, 2.0, 3.0)
p_dict = {"x": 1.0, "y": 2.0, "z": 3.0}
print(f"tuple: {sys.getsizeof(p_tuple)} bytes")
# tuple: 64 bytes on a 64-bit CPython 3.13
print(f"namedtuple: {sys.getsizeof(p_namedtuple)} bytes")
# namedtuple: 64 bytes, the same as a plain tuple: the names live on the type, not on each instance
print(f"dict: {sys.getsizeof(p_dict)} bytes")
# dict: 184 bytes on a 64-bit CPython 3.13 (the hash table costs space, even in compact dicts)These byte counts come from a 64-bit build, which is why this cell is read-only. Pyodide, the Python that runs in your browser, is a 32-bit build. Its pointers are 4 bytes instead of 8, so every size comes out smaller there, and the exact numbers also change between Python versions. The ranking holds everywhere: a namedtuple costs the same as a tuple, and a dict costs several times more.
namedtuples are ideal for representing database rows, coordinates, config snapshots, or any read-only record where you want attribute access without the overhead of a dict.
p = Point(x=3, y=7). You write p._replace(x=10) on its own line and then print p. What do you see?
#deque: O(1) Operations on Both Ends
list is a row of items side by side in memory. Inserting or removing at the left end (insert(0, x), pop(0)) is O(n), because every item must move one place. A deque (say "deck", short for double-ended queue) is built so that both ends are O(1).from collections import deque
dq = deque([1, 2, 3, 4, 5])
dq.append(6) # add on the right end
dq.appendleft(0) # add on the left end, O(1) (list.insert(0, x) is O(n))
print(dq.pop(), dq.popleft()) # 6 0 (take one from each end)
dq.rotate(2) # move 2 items from the right end to the left end
print(list(dq)) # [4, 5, 1, 2, 3]Queues, where the first item in is the first item out, are covered in full in the lesson on Stacks and queues. Here we keep the one deque feature that is most useful on its own.
#Fixed-Size deque: The Sliding Window Pattern
from collections import deque
# maxlen: when full, adding on one end drops an item from the other end
history = deque(maxlen=5)
for i in range(10):
history.append(i)
print(f"Added {i}: {list(history)}")
# Added 0: [0]
# Added 1: [0, 1]
# ...
# Added 5: [1, 2, 3, 4, 5] -- 0 was auto-discarded
# Added 9: [5, 6, 7, 8, 9] -- always the last 5
# Sliding window average (useful for time-series smoothing)
def moving_average(data, window):
"""Average of each run of `window` values, using a deque as the window."""
window_data = deque(maxlen=window)
averages = []
for value in data:
window_data.append(value)
if len(window_data) == window:
averages.append(sum(window_data) / window)
return averages
prices = [10, 12, 11, 14, 15, 13, 16, 18, 17, 20]
ma = moving_average(prices, window=3)
print("Moving average (window=3):", [round(x, 2) for x in ma])
# [11.0, 12.33, 13.33, 14.0, 14.67, 15.67, 17.0, 18.33]sum(window_data) adds up the whole window at every step, so each step costs O(window). Keeping a running total would cost O(1) per step. This version trades speed for clarity.#ChainMap: Layered Dict Lookups
ChainMap groups multiple dicts into a single logical view. Lookups search each map in order. Writes go to the first map.from collections import ChainMap
# Classic use case: layered configuration
defaults = {
"timeout": 30,
"retries": 3,
"debug": False,
"log_level": "INFO",
}
env_vars = {
"timeout": 60,
"debug": True,
}
cli_args = {
"log_level": "DEBUG",
}
# Priority: CLI > env vars > defaults
config = ChainMap(cli_args, env_vars, defaults)
print(config["timeout"]) # 60 (from env_vars)
print(config["retries"]) # 3 (from defaults)
print(config["log_level"]) # "DEBUG" (from cli_args)
print(config["debug"]) # True (from env_vars)
# Writes go to the first map only
config["new_key"] = "hello"
print(cli_args) # {'log_level': 'DEBUG', 'new_key': 'hello'}
print(defaults) # unchanged
# .maps gives access to the underlying list of dicts
print(config.maps) # [cli_args, env_vars, defaults]
# Create a child context (adds a new layer at the front)
child = config.new_child({"timeout": 5})
print(child["timeout"]) # 5 (child override)
print(config["timeout"]) # 60 (parent unchanged)config = ChainMap(cli_args, env_vars, defaults) and config['timeout'] reads 60 from env_vars. You then assign config['timeout'] = 99. Which dict changes?
Priority queues and top-K problems useheapq, which is not covered here. Its full lesson is Heaps & Priority Queues, in the optional data-structures part at the end of the track.
#bisect: Binary Search on Sorted Lists
bisect module does binary search (halve the search range at every step) on a list that is already sorted. The idea is taught in the algorithms lesson. Here is only the Python tool: finding is O(log n), and inserting while staying sorted is O(n), because items must shift.import bisect
scores = [1, 3, 3, 3, 5, 7]
print(bisect.bisect_left(scores, 3)) # 1 (the index before the 3s)
print(bisect.bisect_right(scores, 3)) # 4 (the index after the 3s)
bisect.insort(scores, 4) # insert and keep the list sorted
print(scores) # [1, 3, 3, 3, 4, 5, 7]
# A lookup table: which grade band does a score fall in?
breakpoints, grades = [60, 70, 80, 90], "FDCBA"
print(grades[bisect.bisect(breakpoints, 75)]) # Cgrade() uses bisect([60, 70, 80, 90], score). A student scores exactly 60. What grade comes back?
#Code Playground
Tests: Build a streaming word frequency analyzer with Counter and deque!
A deque is built from small blocks linked together, which is why the ends are cheap and the middle is not. The rule of thumb is enough for now: deque when you work at both ends, list when you index into the middle. The lesson on Stacks and queues shows how it is built.
#Key Takeaways
- Counter is a specialized dict for counting —
Counter(iterable)counts frequencies automatically, supports arithmetic between counters, and.most_common(n)retrieves top-N in one call - defaultdict eliminates missing-key boilerplate — pass a factory (
list,int,set, or a lambda) and missing keys are auto-initialized. Essential for grouping, graph adjacency lists, and inverted indexes - namedtuple creates readable, memory-efficient records — access by name (
p.x) instead of index (p[0]), immutable, and hashable when every field value is hashable, uses far less memory than a dict or class - deque gives O(1) both-end operations —
appendleft/popleftare O(1) where a list is O(n). Usemaxlenfor sliding windows and fixed-size buffers. Prefer deque over list when you work at both ends - bisect enables O(log n) search in sorted lists —
bisect_left/bisect_rightfind insertion points,insortmaintains order. Use for grade lookups and anywhere you keep a sorted list
What does Counter({'a': 3, 'b': 1}) - Counter({'a': 2, 'b': 5}) produce?