Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. containers
10 min read

Collections & Heaps

Lists, dictionaries and sets cover most needs, but some problems want a structure with a specific shape: a tally of how often things appear, a queue you can pop from both ends, a priority queue that always hands back the smallest item, or a sorted list you can search quickly. The standard library ships all of these in the collections, heapq and bisect modules. Choosing the right one often turns a slow, fiddly solution into a short and fast one.

collections

Counter

A Counter is a dictionary that counts things. Give it any iterable, and it maps each distinct item to the number of times it appears:

python
1from collections import Counter
2
3c = Counter("mississippi")
4c                    # Return: Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
5c

Counting the most frequent bytes or letters is the first step of breaking many classical ciphers, and most_common does it in one call. Counters also add and subtract, combining tallies:

python
Counter([1, 1, 2]) + Counter([1, 3])     # Return: Counter({1: 3, 2: 1, 3: 1})

Two strings are anagrams exactly when their counters are equal: Counter(a) == Counter(b).

defaultdict

A defaultdict is a dictionary that creates a missing key's value on first access instead of raising KeyError. You give it a function that makes the default, usually a type like list, int or set. That removes the "is this key here yet?" check from grouping code:

python
1from collections import defaultdict
2
3services = defaultdict(list)
4for name, port in [(

With a plain dictionary, the loop body would need services.setdefault(name, []).append(port) or an if check. defaultdict(int) works the same way for counting, starting each key at 0, and defaultdict(set) collects unique values, such as the neighbors of each node when building a graph by hand.

Warning
Reading a missing key from a defaultdict creates it. Checking if services["ftp"]: silently adds an "ftp" entry with an empty list. Use "ftp" in services to check without creating anything.

deque

A deque (pronounced "deck", short for double-ended queue) supports fast appends and pops at both ends. A list is fast at the end but slow at the front: lst.pop(0) has to shift every remaining item over by one. A deque does it instantly:

python
1from collections import deque
2
3q = deque([1, 2, 3])
4

Given a maxlen, a deque keeps only the most recent items, dropping old ones from the other end as new ones arrive. That's a sliding window with no extra code:

python
1window = deque(maxlen=3)
2for x in range(5):
3    window.append(x)

The most important use of a deque is the queue in a breadth-first search (BFS), which explores outward from a starting point one step at a time, and so finds the shortest path in a grid or maze. Here's BFS over a grid of characters, where # is a wall:

python
1from collections import deque
2
3def shortest_path(grid, start, goal):
4

Popping from the left and appending on the right is what makes this breadth-first: points are explored in the order they were discovered, nearest first. Swapping popleft() for pop() turns it into a depth-first search, which still explores everything but no longer finds shortest paths.

namedtuple

namedtuple creates a lightweight tuple type with named fields, so p.x reads better than p[0]:

python
1from collections import namedtuple
2
3Point = namedtuple("Point", ["x", "y"])
4p =

The class-based typing.NamedTuple, covered in Classes & Objects, does the same thing with type hints and is the more modern way to write it.

heapq

A heap is a structure that always gives you its smallest item quickly, no matter what order items were added in. That's exactly what a priority queue needs: a to-do list where you always work on the most urgent item next. Python's heapq module implements a heap on top of a plain list, which you only touch through its functions:

python
1import heapq
2
3tasks = []
4heapq.heappush(tasks, 5)
5

heapq.heapify(lst) turns an existing list into a heap in place. The list is ordered just enough for the heap to work, not fully sorted, so don't read it directly; always heappop from it.

To attach a priority to an item, push tuples. Tuples compare by their first element, so the priority goes first:

python
1queue = []
2heapq.heappush(queue, (2, "scan ports"))
3heapq.heappush(

heapq only provides a min-heap. For a max-heap, push negated priorities, (-priority, item), and negate them again when you pop. To get the few largest or smallest items without sorting everything, use heapq.nlargest(n, items) and heapq.nsmallest(n, items), which take a key like sorted does:

python
1heapq.nlargest(2, [5, 1, 8, 3])     # Return: [8, 5]
2heapq.nsmallest(2

Dijkstra's Algorithm

BFS finds shortest paths when every step costs the same. When steps have different costs, such as a weighted graph or a grid where some cells are expensive to enter, Dijkstra's algorithm finds the cheapest path instead. It's BFS with the deque swapped for a heap, so the cheapest unexplored point is always expanded next:

python
1import heapq
2
3def dijkstra(graph, start, goal):
4

The direct-looking route through B costs 5, and through C to D costs 8; the heap finds the cheaper detour. NetworkX has Dijkstra built in, but writing it once makes it easy to adapt when a puzzle's "graph" is really a grid with extra state, such as a direction or a number of keys collected.

bisect

The bisect module performs binary search on a sorted list: it finds where a value belongs by repeatedly halving the search range, so it takes about 20 steps even for a million items. bisect_left returns the index of the first position where the value could be inserted, before any equal items, and bisect_right (or plain bisect) returns the position after them:

python
1import bisect
2
3thresholds = [60, 70, 80, 90]
4bisect.bisect_left

That makes it a neat lookup table for ranges, such as turning a score into a letter grade:

python
1def grade(score):
2    return "FDCBA"[bisect.bisect(thresholds, score)]
3
4

bisect.insort(lst, value) inserts a value at its sorted position, keeping the list sorted without re-sorting it:

python
1nums = [1, 4, 9]
2bisect.insort(nums, 5)       # nums = [1, 4, 5, 9]

Intervals

Many puzzles involve ranges of numbers: IP address blocks, time windows, the cells a sensor covers. A common task is merging overlapping ranges. Sorting by start point makes it a single pass: each range either overlaps the last merged one, extending it, or starts a new one:

python
1def merge(intervals):
2    merged = []
3    for start, end in sorted(

When a problem needs more than merging, such as subtracting ranges, intersecting them, or mixing open and closed ends, the third-party portion package does interval arithmetic for you. Install it with uv add portion (see Packages & Environments):

python
1import portion as P
2
3P.closed(1, 5) | P.closed(3, 8

Notice how subtracting [4,6] leaves [1,4) and (6,10]: the parenthesis means the end point itself is excluded, which is exactly the kind of off-by-one detail that's easy to get wrong by hand.

[
"s"
]
# Return: 4
6c["z"] # Return: 0, missing items count as zero instead of raising KeyError
7c.most_common(2) # Return: [('i', 4), ('s', 4)]
"web"
,
80
)
,
(
"web"
,
443
)
,
(
"ssh"
,
22
)
]
:
5 services[name].append(port)
6
7dict(services) # Return: {'web': [80, 443], 'ssh': [22]}
q
.
appendleft
(
0
)
# q = deque([0, 1, 2, 3])
5q.append(4) # q = deque([0, 1, 2, 3, 4])
6q.popleft() # Return: 0
7q.pop() # Return: 4
8q.rotate(1) # q = deque([3, 1, 2]), shifted one step to the right
4
5window # Return: deque([2, 3, 4], maxlen=3)
queue
=
deque
(
[
(
start
,
0
)
]
)
5 seen = {start}
6 while queue:
7 (x, y), dist = queue.popleft()
8 if (x, y) == goal:
9 return dist
10 for dx, dy in [(0, -1), (1, 0), (0, 1), (-1, 0)]:
11 nx, ny = x + dx, y + dy
12 if 0 <= ny < len(grid) and 0 <= nx < len(grid[0]) and grid[ny][nx] != "#" and (nx, ny) not in seen:
13 seen.add((nx, ny))
14 queue.append(((nx, ny), dist + 1))
15 return None
16
17maze = ["..#",
18 ".##",
19 "..."]
20shortest_path(maze, (0, 0), (2, 2)) # Return: 4
Point
(
3
,
4
)
5p.x # Return: 3
heapq
.
heappush
(
tasks
,
1
)
6heapq.heappush(tasks, 3)
7heapq.heappop(tasks) # Return: 1, always the smallest
8heapq.heappop(tasks) # Return: 3
queue
,
(
1
,
"check creds"
)
)
4heapq.heappop(queue) # Return: (1, 'check creds')
,
[
5
,
1
,
8
,
3
]
)
# Return: [1, 3]
queue
=
[
(
0
,
start
)
]
5 best = {start: 0}
6 while queue:
7 cost, node = heapq.heappop(queue)
8 if node == goal:
9 return cost
10 if cost > best[node]:
11 continue # a stale entry; a cheaper route was already found
12 for neighbor, weight in graph[node]:
13 new_cost = cost + weight
14 if new_cost < best.get(neighbor, float("inf")):
15 best[neighbor] = new_cost
16 heapq.heappush(queue, (new_cost, neighbor))
17 return None
18
19graph = {
20 "A": [("B", 4), ("C", 1)],
21 "C": [("B", 2), ("D", 7)],
22 "B": [("D", 1)],
23 "D": [],
24}
25dijkstra(graph, "A", "D") # Return: 4, by A -> C -> B -> D
(
thresholds
,
70
)
# Return: 1
5bisect.bisect_right(thresholds, 70) # Return: 2
grade
(
85
)
# Return: 'B'
5grade(59) # Return: 'F'
intervals
)
:
4 if merged and start <= merged[-1][1]:
5 merged[-1][1] = max(merged[-1][1], end)
6 else:
7 merged.append([start, end])
8 return merged
9
10merge([(1, 3), (8, 10), (2, 6), (9, 12)]) # Return: [[1, 6], [8, 12]]
)
# Return: [1,8], the union
4P.closed(1, 5) & P.closed(3, 8) # Return: [3,5], the intersection
5P.closed(1, 10) - P.closed(4, 6) # Return: [1,4) | (6,10]
67 in P.closed(1, 5) | P.closed(6, 9) # Return: True