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) \).
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
How Sets Achieve \( O(1) \) Lookup
The Golden Rule of Pythonic Speed
Repeated calculation inside loop
Precomputed value before loop
\( O(n) \) vs \( O(1) \): The Visual Gap
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
Example 1: Set Membership
Example 2: Precomputing Values
Example 3: Both Techniques Together
Problem: Find all students whose GPA is above average AND who are in the honors list.
Common Precomputing Patterns
Decision Flowchart
Beyond the Basics: More Patterns
Common Mistakes
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
Code A:
for item in data:
total = sum(data)
result.append(item / total)
Code B:
total = sum(data)
for item in data:
result.append(item / total)
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?
for name in employees:
valid = set(approved_names)
if name in valid:
grant_access(name)
Question 5 of 5
Which Python expression finds the common elements between two sets most efficiently?