Sub topic 14
Choosing between lists, hash maps and ordered structures
This chapter assumes you know Python lists, dicts and sets, and basic Big-O notation. It also assumes you have seen how a hash table gets average constant-time lookups. Here the goal is a decision procedure: given a task, which structure fits?
Start from the operation you need
Pick the structure by the operation your code performs most often, not by habit.
| Need | Best fit | Typical cost |
|---|---|---|
| Access by position, keep duplicates, keep insertion sequence | list | index O(1), search O(n) |
| "Have I seen this?" or deduplicate | set | O(1) average |
| Look up a value by a key | dict (hash map) | O(1) average |
| Smallest or largest item, or items in sorted order | sorted list, heap, or balanced tree | O(log n) per operation |
| Range queries ("all keys between 10 and 20") | sorted structure | O(log n + k) for k results |
When a list is the right answer
A hash set is not free. It stores a hash and a slot for every element, so it uses more memory than a list. It also needs hashable elements and loses position. For a handful of items, a linear scan over a list is as fast in practice and simpler.
Switch to a set when the collection is large and you test membership repeatedly:
import time
items = list(range(20_000))
queries = range(19_000, 21_000)
as_set = set(items)
start = time.perf_counter()
hits_list = sum(1 for q in queries if q in items)
t_list = time.perf_counter() - start
start = time.perf_counter()
hits_set = sum(1 for q in queries if q in as_set)
t_set = time.perf_counter() - start
print(hits_list == hits_set) # True
print(t_set < t_list) # True on typical machinesBuilding the set costs O(n) once. It pays off only if you query many times.
When hash-based structures are the wrong tool
Hashing scatters keys on purpose, so it cannot answer questions that depend on order or closeness.
- Ordered queries. Finding the smallest key means scanning every key, which is O(n). A heap gives you the minimum in O(1) and removal in O(log n).
- Range queries. A hash map cannot find keys between two bounds without checking all of them. A sorted list with binary search can.
- Nearest neighbor. Finding the closest key to a value needs ordering.
- Untrusted keys. Adversarial input can force many collisions and degrade operations toward O(n). Use a structure with a guaranteed worst case, or rely on a runtime that randomizes hashing.
Here is a range query done with a sorted list and the bisect module:
from bisect import bisect_left, bisect_right
timestamps = [3, 8, 15, 22, 30, 41, 57]
lo = bisect_left(timestamps, 10)
hi = bisect_right(timestamps, 41)
print(timestamps[lo:hi]) # [15, 22, 30, 41]Common mistakes
- Using
x in some_listinside a loop over a large list. This is a hidden O(n²). Convert the list to a set first. - Converting to a set when you need duplicates or positions. A set discards both.
- Choosing a dict when a set is enough. If you never use the values, store only the keys.
- Keeping a sorted structure and then mutating it without keeping it sorted.
Exercise
A service keeps 1 million user IDs. It must (a) check whether an ID is blocked, and (b) report all IDs between 5000 and 6000. Which structures would you use?
Show answer
Use a set for the blocked check, which is O(1) on average. For the range report, keep a sorted list of IDs (or a tree) and use binary search to find the bounds in O(log n), then read the matching slice. A hash set cannot answer the range query without scanning all 1 million IDs.
Exercise
A loop checks if name in names for each of 50,000 incoming records, where names is a list of 50,000 strings. What is the problem, and what is the fix?
Show answer
Each in test scans the list, so the loop does about 50,000 × 50,000 comparisons in the worst case, which is O(n²). Build names_set = set(names) once and test against the set, which makes each check O(1) on average.