Sub topic 14
Common mistakes and how to avoid them
This chapter assumes you know Python lists, dictionaries and sets, and have a rough idea of Big-O. It collects the selection mistakes that cause most real problems. Each one comes from skipping a step in the checklist from the previous chapter: name the operations, estimate how often each runs, then match them to a structure.
Mistake 1: Using a list for repeated membership checks
A list scans element by element for in. A set uses a hash lookup. If you test membership many times, convert once and test against the set.
names_list = ["ada", "grace", "alan"]
names_set = set(names_list)
print("grace" in names_list) # True, scans the list: O(n)
print("grace" in names_set) # True, hash lookup: O(1) on averageBuilding the set costs O(n) once. That pays off when you do many lookups. For one or two lookups on a small list, the list is fine.
Mistake 2: Removing from the front of a list
list.pop(0) shifts every remaining element left, so it costs O(n). Using it in a loop makes the whole loop O(n²). This often appears in breadth-first search.
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return order
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs_order(graph, "a")) # ['a', 'b', 'c', 'd']This example avoids two mistakes. The deque removes from the front in O(1). The seen set stops the search from revisiting nodes, which would otherwise loop forever on a cycle.
Mistake 3: Using unhashable or mutable keys
Dictionary keys and set members must be hashable. A mutable object such as a list could change after insertion and no longer match its stored hash. Python refuses them.
try:
lookup = {[1, 2]: "pair"}
except TypeError as error:
print(error) # unhashable type: 'list'
lookup = {(1, 2): "pair"}
print(lookup[(1, 2)]) # pairUse a tuple, a string, a number or a frozenset instead. A tuple that contains a list is still unhashable, so check nested contents too.
Mistake 4: Sorting everything when you need a few items
A full sort costs O(n log n). If you only need the top few items, or you keep asking for the smallest item as data arrives, a heap does less work.
import heapq
scores = [42, 7, 19, 88, 63, 5]
print(heapq.nlargest(3, scores)) # [88, 63, 42]
heap = []
for s in scores:
heapq.heappush(heap, s)
print(heapq.heappop(heap)) # 5, the smallest itemMistake 5: Using a hash table when you need order
A hash table answers "is this key present?" but not "what is the next larger key?". For neighbor or range queries, keep a sorted list and use binary search.
import bisect
sorted_ids = [10, 20, 30, 40]
i = bisect.bisect_left(sorted_ids, 25)
print(i, sorted_ids[i]) # 2 30
bisect.insort(sorted_ids, 25)
print(sorted_ids) # [10, 20, 25, 30, 40]Finding the position is O(log n). Inserting still shifts elements, so this suits data that is read far more often than it changes. For heavy inserts plus ordered queries, consider a balanced search tree from a library.
Quick reference
| Symptom | Likely mistake | Better choice |
|---|---|---|
| Slow `x in collection` inside a loop | List used for membership | `set` or `dict` |
| Queue loop is slow on big inputs | `pop(0)` on a list | `collections.deque` |
| `TypeError: unhashable type` | Mutable key | Tuple or `frozenset` |
| Sorting just to take a few items | Full sort | `heapq` |
| Need next larger value or a range | Hash table | Sorted list with `bisect`, or a tree |
A habit that prevents most of these
Before you commit to a structure, write down the two or three operations that run most often and what each costs. Then measure with realistic input sizes. Asymptotic costs guide the choice, but constant factors and memory layout can decide close cases, so a quick timing test with timeit settles doubts.
Exercise
A function checks whether each of 100,000 incoming IDs appears in a list of 50,000 known IDs, using if id in known_ids. What is the problem, and what is the fix?
Show answer
Each in test on a list scans up to 50,000 items, so the total work is roughly 100,000 × 50,000 comparisons. Convert the list to a set once with known = set(known_ids) and test id in known. Each check then costs O(1) on average.
Exercise
You want to use the pair of a user's latitude and longitude, stored as a list [lat, lon], as a dictionary key. What happens, and how do you fix it?
Show answer
Python raises TypeError: unhashable type: 'list' because lists are mutable. Convert the pair to a tuple, (lat, lon), and use that as the key.