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.
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:
1from collections import Counter
2
3c = Counter("mississippi")
4c # Return: Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
5cCounting 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:
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).
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:
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.
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.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:
1from collections import deque
2
3q = deque([1, 2, 3])
4Given 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:
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:
1from collections import deque
2
3def shortest_path(grid, start, goal):
4Popping 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 creates a lightweight tuple type with named fields, so p.x reads better than p[0]:
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.
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:
1import heapq
2
3tasks = []
4heapq.heappush(tasks, 5)
5heapq.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:
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:
1heapq.nlargest(2, [5, 1, 8, 3]) # Return: [8, 5]
2heapq.nsmallest(2BFS 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:
1import heapq
2
3def dijkstra(graph, start, goal):
4The 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.
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:
1import bisect
2
3thresholds = [60, 70, 80, 90]
4bisect.bisect_leftThat makes it a neat lookup table for ranges, such as turning a score into a letter grade:
1def grade(score):
2 return "FDCBA"[bisect.bisect(thresholds, score)]
3
4bisect.insort(lst, value) inserts a value at its sorted position, keeping the list sorted without re-sorting it:
1nums = [1, 4, 9]
2bisect.insort(nums, 5) # nums = [1, 4, 5, 9]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:
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):
1import portion as P
2
3P.closed(1, 5) | P.closed(3, 8Notice 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.