Faster with the right data structure
Big-O in plain words: lists vs sets vs dicts.
🎬 Video version coming soon — read it now
The biggest speed-ups rarely come from clever tricks. They come from choosing the right data structure, changing how the work grows as data grows.
Big-O in plain words
Big-O describes how the work grows when the data grows:
- O(1), constant: the same time whether you have 10 items or 10 million. Dictionary and set lookups.
- O(n), linear: twice the data, twice the time. Looping over a list once;
x in some_list. - O(n log n): a little more than linear. Sorting.
- O(n²), quadratic: twice the data, four times the time. A loop inside a loop over the same data.
At 100 items, nobody notices. At 100,000 items, O(n²) is ten billion steps.
The most common slow pattern
# Checking membership in a list, inside a loop: O(n²)
registered = [f"user{i}" for i in range(50_000)]
attendees = [f"user{i}" for i in range(0, 100_000, 2)]
present = [a for a in attendees if a in registered] # slowa in registered scans the list from the start each time. Fix it with a set:
registered_set = set(registered)
present = [a for a in attendees if a in registered_set] # fastSame result, but each lookup is O(1). On this data it's roughly a thousand times faster. Try it with %timeit.
Choose by the question you ask most
- "Is x in here?": set (or dict keys)
- "What's the value for key k?": dict
- "Items in order, by position": list
- "Add or remove at both ends": collections.deque
- "Always get the smallest or largest next": heapq
- "Count things": Counter
Other quick wins
# Build strings with join, not += in a loop
line = ", ".join(names)
# Use built-ins: they run in C
total = sum(values)
biggest = max(values)
# Avoid repeated work inside loops
upper_names = {n.upper() for n in names} # compute onceWhen data gets big: NumPy and pandas
For numeric work on large arrays, NumPy runs whole-array operations in optimised C:
import numpy as np
a = np.arange(10_000_000)
print((a * a).sum()) # much faster than a Python loopYou'll use NumPy and pandas heavily in the Python for AI course.
In one line
Pick data structures by your most common operation (sets and dicts for lookups) and avoid accidental O(n²) loops; that beats any micro-trick.
Share with a friend