01 / 20

Pythonic
Optimizations

Learn how to write faster Python code using set membership testing, precomputing values, and idiomatic patterns that reduce time complexity from \( O(n) \) to \( O(1) \).

Python

Why Write Faster Python?

Python is known for readability and simplicity, but naive code can be orders of magnitude slower than optimized code. The good news: most speedups come from choosing the right data structure and avoiding redundant work, not from rewriting in C.

Two Core Optimization Ideas

Set Membership
Replace list lookups with set lookups. Sets use hash tables internally, giving \( O(1) \) average-case membership testing instead of \( O(n) \).
Precomputing
Calculate expensive values once before a loop, then reuse them. Avoid repeating the same computation inside every iteration.

How Sets Achieve \( O(1) \) Lookup

HASH TABLE (set internals) Bucket 0 Bucket 1 Bucket 2 Bucket 3 Bucket 4 "cat" "dog" "fox" "dog" in my_set hash("dog") % 5 = 2 Found in O(1)!

The Golden Rule of Pythonic Speed

Slow Pattern
list lookup: \( O(n) \) per check
Repeated calculation inside loop
Fast Pattern
set lookup: \( O(1) \) per check
Precomputed value before loop

\( O(n) \) vs \( O(1) \): The Visual Gap

n (number of elements) Time per lookup 0 250k 500k 750k 1M list O(n) set O(1) Gap grows with n

With 1 million elements, a list membership check scans up to 1M items. A set check? Still just one hash computation. The bigger your data, the bigger the payoff.

List vs Set: Key Differences

list set
Membership test \( O(n) \) \( O(1) \) avg
Ordered? Yes (insertion order) No
Duplicates? Allowed Not allowed
Indexable? Yes: my_list[i] No
Creation [1, 2, 3] {1, 2, 3}
Best for Ordered sequences Fast lookups

Step-by-Step Optimization Checklist

1
Identify your loop. Find the hot loop where your program spends most of its time.
2
Spot membership checks. Do you use x in my_list inside the loop? Convert my_list to a set before the loop.
3
Find repeated calculations. Is the same expression computed every iteration? Move it above the loop.
4
Measure the difference. Use time.time() or timeit to verify your optimization actually helped.

Example 1: Set Membership

✕ Slow: list lookup
banned = ["spam", "ads", "scam"] for word in message: if word in banned: # O(n) each flag(word)
✓ Fast: set lookup
banned = {"spam", "ads", "scam"} for word in message: if word in banned: # O(1) each flag(word)

Example 2: Precomputing Values

✕ Slow: repeated work
for x in data: avg = sum(data) / len(data) diff = x - avg # sum() recalculated every # iteration: O(n) * n = O(n^2)
✓ Fast: precomputed
avg = sum(data) / len(data) for x in data: diff = x - avg # sum() computed once # total: O(n) + O(n) = O(n)

Example 3: Both Techniques Together

Problem: Find all students whose GPA is above average AND who are in the honors list.

# Slow: O(n^2) total honors_list = ["Alice", "Bob", "Carol", ...] # 5,000 names for s in students: avg = sum(g.gpa for g in students) / len(students) if s.gpa > avg and s.name in honors_list: # O(n) lookup result.append(s)
# Fast: O(n) total honors_set = set(honors_list) # Convert once: O(n) avg = sum(s.gpa for s in students) / len(students) # Precompute for s in students: if s.gpa > avg and s.name in honors_set: # O(1) lookup result.append(s)

Common Precomputing Patterns

Prefix Sums
Build a running total array once, then answer any "sum of subarray" query in \( O(1) \) instead of \( O(n) \).
Lookup Dicts
Build a dictionary mapping keys to values before the loop. Replaces repeated linear search with \( O(1) \) dict access.
Cached Results
Store the result of an expensive function call (e.g., len(), max()) in a variable before the loop.

Decision Flowchart

Code in a loop? Uses "x in collection"? Yes Convert to set No Computes same value each iteration? Yes Move above loop No Builds a list just for counting/checking? Yes Use set or generator No Code is likely fine

Beyond the Basics: More Patterns

1
Use generators over lists when you only iterate once. sum(x*x for x in data) avoids creating an intermediate list in memory.
2
dict.get() with default instead of checking "if key in dict" then accessing. One hash lookup instead of two.
3
Local variable caching: Assign len_data = len(data) before a tight loop. Avoids repeated method dispatch.
4
set operations for bulk comparisons: set_a & set_b finds intersection faster than nested loops.

Common Mistakes

✕ Converting inside the loop
Writing set(my_list) inside each iteration. The conversion itself is \( O(n) \), negating the benefit. Convert once before the loop.
✕ Using set for ordered data
Sets are unordered. If you need to preserve insertion order and also need fast lookups, use a dict (keys are ordered since Python 3.7).
✕ Premature optimization
Optimizing code that runs once with 10 items. Profile first with timeit to confirm the bottleneck before changing data structures.

Summary of Optimizations

Pattern Before After Speedup
Membership test x in list x in set \( O(n) \) → \( O(1) \)
Precompute value Inside loop Before loop \( O(n^2) \) → \( O(n) \)
Intersection Nested loops set_a & set_b \( O(nm) \) → \( O(\min(n, m)) \)
Generator expr sum([...list...]) sum(...gen...) Less memory

Question 1 of 5

What is the average time complexity of checking x in my_set where my_set is a Python set?

Question 2 of 5

If data has \( n \) elements, what is the time complexity of Code A vs Code B?

Question 3 of 5

You have a list of 50,000 usernames and need to check whether each of 100,000 login attempts matches a valid username. Which approach is most efficient?

Question 4 of 5

What is wrong with this code?

Question 5 of 5

Which Python expression finds the common elements between two sets most efficiently?