Big-O for
Lists & Dicts
Understand how loops, nested loops, and common operations on Python lists and dicts affect your program's speed: from \( O(1) \) to \( O(n^2) \).
What Is Big-O Notation?
Big-O describes how the number of steps your code takes grows as the input size \( n \) increases. It ignores constants and focuses on the worst-case growth rate.
Visualizing Growth Rates
Why Big-O Matters in Python
Python makes it easy to write clean code, but hidden performance traps lurk inside common operations. Knowing Big-O helps you predict whether your program will finish in milliseconds or minutes.
x in my_list is \( O(n) \), but x in my_dict is \( O(1) \)The Loop Rule
List vs Dict Membership
Sequential vs Nested Loops
\( O(n) + O(n) = O(2n) = \) \( O(n) \)
Constants are dropped, so sequential loops stay linear.
\( O(n) \times O(n) = \) \( O(n^2) \)
Each iteration of the outer loop runs the entire inner loop.
Python Operations Cheat Sheet
| Operation | List | Dict / Set |
|---|---|---|
| Index / Key lookup | \( O(1) \) | \( O(1) \) |
Membership: x in |
\( O(n) \) | \( O(1) \) |
| Append / Insert end | \( O(1) \) | \( O(1) \) |
| Insert at position 0 | \( O(n) \) | N/A |
| Delete by value | \( O(n) \) | \( O(1) \) |
| Iteration (for loop) | \( O(n) \) | \( O(n) \) |
| Sort | \( O(n \log n) \) | N/A |
How to Analyze Your Code
x in my_list inside the loop?Example 1: Simple Loop
Example 2: Nested Loop
Example 3: Hidden \( O(n) \) Inside a Loop
The Set/Dict Fix Pattern
Dropping Constants & Lower Terms
Big-O only cares about the dominant term as \( n \rightarrow \infty \). Constants and smaller terms vanish:
Common Mistakes
x in my_list is \( O(1) \). Lists require a full scan: it is \( O(n) \).Question 1 of 5
What is the time complexity of checking x in my_list where my_list has \( n \) elements?
x. In the worst case, it checks all \( n \) elements, making it \( O(n) \).Question 2 of 5
Two sequential (not nested) loops each run \( n \) times. What is the overall complexity?
Question 3 of 5
Consider this code:
for i in range(n):
if i in my_dict:
print(i)
where my_dict is a Python dictionary.
What is the overall time complexity of this code?
i in my_dict is \( O(1) \) for a dictionary. Total: \( O(n) \times O(1) = O(n) \).Question 4 of 5
Consider this code:
for i in range(n):
for j in range(n):
total += i * j
What is the time complexity?
Question 5 of 5
Consider this code:
for x in list_a:
if x in list_b:
result.append(x)
Both list_a and list_b have \( n \) elements.
A student changes list_b to a set. What does the complexity become?
x in set_b is \( O(1) \). The loop runs \( n \) times. Total: \( O(n) \times O(1) = O(n) \). Building the set costs \( O(n) \) too, so overall: \( O(n) \).