Concept Explanation
Profiling tells you where the time went. Big-O tells you why, and whether the problem will get worse.
Big-O describes how runtime grows as input grows. It ignores constants deliberately, because at scale they stop mattering: an O(n²) algorithm with a fast inner loop still loses to an O(n) algorithm with a slow one, given enough data.
| Complexity | Name | n = 1,000 | n = 1,000,000 |
|---|---|---|---|
| O(1) | Constant | 1 step | 1 step |
| O(log n) | Logarithmic | 10 | 20 |
| O(n) | Linear | 1,000 | 1,000,000 |
| O(n log n) | Linearithmic | 10,000 | 20,000,000 |
| O(n²) | Quadratic | 1,000,000 | 1,000,000,000,000 |
Look at the last row. Scaling an O(n²) algorithm from a thousand items to a million makes it a million times slower, not a thousand. That is why quadratic code passes every test on your sample data and dies in production.
Python's Actual Costs
Most "why is this slow" bugs come from not knowing what a built-in operation costs:
| Operation | List | Set / Dict | Deque |
|---|---|---|---|
x in c | O(n) | O(1) | O(n) |
c[i] | O(1) | O(1) by key | O(n) |
c.append(x) | O(1) amortised | — | O(1) |
c.insert(0, x) | O(n) | — | O(1) |
c.pop() | O(1) | — | O(1) |
c.pop(0) | O(n) | — | O(1) |
del c[i] | O(n) | O(1) | O(n) |
The bolded rows are where real programs lose their time. if item in my_list inside a loop over n items is O(n²) written in a way that looks completely innocent.
The Three Rules That Cover Most Cases
- Nested loops over the same data multiply. Two loops over n is O(n²).
- Halving the search space each step is logarithmic. Binary search on a sorted list is O(log n).
- A loop containing an O(n) operation is O(n²). This includes
inon a list,list.pop(0), string concatenation in a loop, anddf.appendin pandas.
String Concatenation
Strings are immutable, so result += piece builds a new string every time, copying everything so far:
# O(n^2) -- copies the accumulated string on every iteration
result = ""
for piece in pieces:
result += piece
# O(n) -- one allocation at the end
result = "".join(pieces)
CPython has an optimisation that sometimes rescues the first form, but it only applies when the string has a single reference, and it does not apply to lists or DataFrames at all. Use join.
Amortised Analysis
list.append is "O(1) amortised": most appends are instant, but occasionally the list is full and everything gets copied to a bigger array. Averaged over many appends, the cost per operation is constant. This is why building a list with append and converting at the end is fast, while inserting at the front repeatedly is not.
Space Complexity Matters Too
An algorithm that is fast but allocates a copy of your dataset can be worse than a slower one that works in place. Generators are the main tool here: sum(x*x for x in data) uses O(1) extra memory, while sum([x*x for x in data]) builds the whole list first.
Code Example #1 (Basic)
The list-versus-set lookup, measured.
import random
import time
from bisect import bisect_left
random.seed(0)
haystack_list = list(range(200_000))
haystack_set = set(haystack_list)
needles = [random.randrange(200_000) for _ in range(2_000)]
def timed(label, fn):
start = time.perf_counter()
result = fn()
elapsed = time.perf_counter() - start
print(f"{label:<34} {elapsed * 1000:>9.2f} ms (found {result})")
return elapsed
# O(n) per lookup -> O(n*m) overall
t_list = timed("list membership (O(n) each)",
lambda: sum(1 for x in needles if x in haystack_list))
# O(1) per lookup -> O(m) overall
t_set = timed("set membership (O(1) each)",
lambda: sum(1 for x in needles if x in haystack_set))
# O(log n) per lookup -- when you must keep sorted order
def binary_search_count():
found = 0
for x in needles:
i = bisect_left(haystack_list, x)
if i < len(haystack_list) and haystack_list[i] == x:
found += 1
return found
t_bisect = timed("bisect on sorted list (O(log n))", binary_search_count)
print(f"\nset is {t_list / t_set:,.0f}x faster than list membership")
print(f"bisect is {t_list / t_bisect:,.0f}x faster, and keeps the list sorted\n")
# --- The front-insertion trap ---
from collections import deque
N = 60_000
start = time.perf_counter()
lst = []
for i in range(N):
lst.insert(0, i) # O(n) each -> O(n^2) total
list_time = time.perf_counter() - start
start = time.perf_counter()
dq = deque()
for i in range(N):
dq.appendleft(i) # O(1) each -> O(n) total
deque_time = time.perf_counter() - start
print(f"list.insert(0, x) x{N:,}: {list_time * 1000:>8.1f} ms")
print(f"deque.appendleft() x{N:,}: {deque_time * 1000:>8.1f} ms")
print(f"deque is {list_time / deque_time:,.0f}x faster for front insertion")
The ratios are the point. These are not micro-optimisations of a few percent — swapping a list for a set on a membership check routinely turns a minute into a millisecond, and it is a one-word change.
Code Example #2 (Intermediate)
Measuring growth rates directly, and fixing a quadratic algorithm.
import random
import time
from collections import Counter, defaultdict
def measure(fn, sizes):
"""Run fn at several input sizes and report how the time actually scaled."""
results = []
for n in sizes:
data = [random.randrange(n * 2) for _ in range(n)]
start = time.perf_counter()
fn(data)
results.append((n, time.perf_counter() - start))
return results
def report(label, results):
print(f"\n{label}")
print(f" {'n':>8} {'time (ms)':>11} {'ratio':>8} behaviour")
prev = None
for n, t in results:
if prev is None:
print(f" {n:>8,} {t * 1000:>11.2f} {'--':>8}")
else:
ratio = t / prev if prev > 0 else 0
# Input doubled: ~2x => linear, ~4x => quadratic
shape = ("linear" if ratio < 2.6 else
"n log n" if ratio < 3.2 else "QUADRATIC")
print(f" {n:>8,} {t * 1000:>11.2f} {ratio:>7.1f}x {shape}")
prev = t
random.seed(1)
SIZES = [2_000, 4_000, 8_000, 16_000]
# ---------- Problem: find duplicates ----------
def duplicates_quadratic(data):
"""O(n^2): for every item, scan everything seen so far."""
seen, dupes = [], []
for item in data:
if item in seen: # O(n) inside an O(n) loop
dupes.append(item)
else:
seen.append(item)
return dupes
def duplicates_linear(data):
"""O(n): one hash lookup per item."""
seen, dupes = set(), []
for item in data:
if item in seen: # O(1)
dupes.append(item)
else:
seen.add(item)
return dupes
report("Duplicate detection -- list of seen items", measure(duplicates_quadratic, SIZES))
report("Duplicate detection -- set of seen items", measure(duplicates_linear, SIZES))
# ---------- Problem: group records by key ----------
records = [{"user": random.randrange(500), "amount": random.random() * 100}
for _ in range(40_000)]
def group_quadratic(records):
"""O(n*k): re-scan every record for each distinct key."""
keys = set(r["user"] for r in records)
return {k: [r["amount"] for r in records if r["user"] == k] for k in keys}
def group_linear(records):
"""O(n): one pass, dict of lists."""
out = defaultdict(list)
for r in records:
out[r["user"]].append(r["amount"])
return out
for label, fn in [("group: filter per key", group_quadratic),
("group: single pass ", group_linear)]:
start = time.perf_counter()
result = fn(records)
print(f"\n{label} {(time.perf_counter() - start) * 1000:>8.1f} ms "
f"({len(result)} groups)")
# ---------- Problem: build a string ----------
pieces = [f"row-{i}," for i in range(120_000)]
start = time.perf_counter()
slow = ""
for p in pieces:
slow += p # new string allocated each time
concat_time = time.perf_counter() - start
start = time.perf_counter()
fast = "".join(pieces) # one allocation
join_time = time.perf_counter() - start
print(f"\nstring += in a loop: {concat_time * 1000:>8.1f} ms")
print(f'"".join(pieces): {join_time * 1000:>8.1f} ms')
print(f"join is {concat_time / join_time:,.0f}x faster (same result: {slow == fast})")
# ---------- Space: generator vs list ----------
import sys
nums = range(1_000_000)
listcomp = [x * x for x in nums]
genexp = (x * x for x in nums)
print(f"\nlist comprehension holds: {sys.getsizeof(listcomp) / 1_000_000:.1f} MB")
print(f"generator expression holds: {sys.getsizeof(genexp)} bytes")
print("Same sum, O(n) vs O(1) memory -- matters when the data does not fit in RAM.")
The ratio column in report is a technique worth keeping. Double the input and time it: roughly 2× slower means linear, roughly 4× means quadratic. You do not need to analyse the code — you can measure the exponent directly, which is far more reliable than reasoning about a function you did not write.
Common Mistakes
if x in my_listinside a loop: the classic accidental O(n²). Convert to a set first.list.pop(0)orlist.insert(0, x)in a loop: every operation shifts the whole list. Usecollections.deque.- Building strings with
+=in a loop: quadratic copying. Use"".join(). df.append()orpd.concatinside a loop: pandas copies the entire DataFrame each time. Collect rows in a list and build once.- Re-filtering a list for every key:
[r for r in rows if r.key == k]inside a loop over keys. One pass with adefaultdictinstead. - Sorting inside a loop:
sorted()is O(n log n); doing it n times is O(n² log n). Sort once outside. - Optimising the wrong thing: a 10× speedup on code that takes 2% of runtime buys you 1.8%. Profile first.
- Assuming constants never matter: for n = 20, an O(n²) algorithm with a tight loop often beats an O(n log n) one with overhead. Big-O is about growth, not small inputs.
- Ignoring memory: a list comprehension over ten million rows may work; over a billion it will not. Generators cost nothing to try.
- Recomputing inside a loop:
len(data)orexpensive(config)evaluated on every iteration when the result never changes. - Using
list.remove()ordelin a loop: each is O(n), and mutating while iterating also skips elements.
Best Practices
- Reach for a
setordictthe moment you writeinon a collection you will search more than once. - Use
collections.dequefor queues —appendleftandpopleftare O(1). - Build with
appendand join at the end, for strings, lists, and DataFrames alike. - Measure the growth rate: run at n, 2n, and 4n and look at the ratios. It identifies quadratic code in seconds.
- Do one pass and group into a
defaultdictrather than filtering repeatedly. - Hoist invariants out of loops: anything whose value cannot change should be computed once.
- Prefer generators when you only iterate once — O(1) memory for free.
- Know the complexity of the built-in you are calling. Most performance bugs are a hidden O(n) inside a loop.
- Profile before optimising, and measure after. Intuition about Python performance is unreliable in both directions.
- Accept a worse complexity for small, fixed n — clarity wins when the data cannot grow.
- Use
bisectwhen you need both order and fast lookup, andheapqwhen you repeatedly need the smallest item.
Practice Exercises
- The Growth Test: Write a function containing a nested loop and time it at n = 1,000, 2,000, 4,000, and 8,000. Print the ratio between consecutive timings and confirm it lands near 4× rather than 2×.
- The Membership Fix: Build a 100,000-element list and time 5,000
inlookups against it, then against a set built from the same data. Report the speedup and the one line you had to change. - The Quadratic Hunt: Write a function that groups 50,000 records by key using a filter-per-key approach, then rewrite it with a single-pass
defaultdict. Time both and explain in a comment which of the three rules the original violated.