Sub topic 12
Hidden Loops in Built-in Operations
This chapter assumes you can count single and nested loops, add and multiply costs, and reduce exact counts to Big-O. Here we apply those skills to code that looks loop-free but isn't.
One Line Is Not One Step
Earlier chapters treated a step as a constant-time operation. Many Python built-ins break that assumption. They are short to write, but inside they run a loop over their input. If you count such a call as one step, your estimate can be off by a whole factor of n.
Take this function:
def common_items(a, b):
result = []
for x in a: # len(a) iterations
if x in b: # list membership scans b: up to len(b) steps
result.append(x)
return resultThe visible loop runs len(a) times. The test x in b on a list compares x with each element of b in turn until it finds a match. In the worst case, when x is not in b, that is len(b) comparisons. So the function is really a nested loop, and its worst-case cost is O(len(a) · len(b)). With two lists of 10,000 items each, that comes to as many as 100 million comparisons.
Making the Hidden Loop Visible
Writing the built-in out by hand shows its cost clearly:
def contains(seq, target):
steps = 0
for item in seq:
steps += 1
if item == target:
return True, steps
return False, steps
b = list(range(10_000))
print(contains(b, 9_999)) # (True, 10000)
print(contains(b, -1)) # (False, 10000)This is the same early-exit pattern from the previous chapter, so the best case is 1 step and the worst case is m steps.
Fixing It by Changing the Data Structure
A set stores items in a hash table. A membership test hashes the value and checks one bucket, so its average cost is O(1).
def common_items_fast(a, b):
b_set = set(b) # one pass over b: O(m)
return [x for x in a if x in b_set] # n lookups, average O(1) each
a = list(range(0, 20, 2))
b = list(range(0, 20, 3))
print(common_items_fast(a, b)) # [0, 6, 12, 18]The sequential cost is O(m) to build the set plus O(n) for the lookups, which gives O(n + m) on average. Building the set has a cost of its own, so this change pays off when you test many values against the same collection.
Common Built-ins and Their Real Cost
In the table below, n is the length of the list or string involved and k is the size of a slice or of the added data.
| Operation | Typical cost | Why |
|---|---|---|
| `len(lst)` | O(1) | Length is stored |
| `lst.append(x)` | O(1) amortized | Occasional resize spread over many appends |
| `lst.pop()` | O(1) | Removes from the end |
| `x in lst`, `lst.index(x)`, `lst.remove(x)` | O(n) | Linear scan |
| `lst.insert(0, x)`, `lst.pop(0)` | O(n) | Shifts every element |
| `lst[i:j]` | O(k) | Copies k = j − i items |
| `min(lst)`, `max(lst)`, `sum(lst)` | O(n) | Visits every item |
| `sorted(lst)`, `lst.sort()` | O(n log n) | Comparison sort |
| `x in s` for a set, `d[key]` for a dict | O(1) average | Hash lookup |
| `"".join(parts)` | O(total length) | One pass over all characters |
A frequent mistake is calling one of the O(n) operations inside a loop. For example, while queue: item = queue.pop(0) drains a list in O(n²). Using collections.deque with popleft() brings it down to O(n).
Exercise
What is the worst-case cost of this function for a list of length n, and how would you make it O(n log n) or better? def has_duplicate(lst): for i in range(len(lst)): if lst[i] in lst[i + 1:]: return True return False
Show answer
Each iteration builds the slice lst[i+1:], which copies n − i − 1 items, and then scans that slice with in. Both are O(n − i). Summed over i, that gives about n(n−1)/2 steps for each, so the function is O(n^2) in the worst case (no duplicates). Sorting the list and comparing neighbors gives O(n log n). Using a set gives O(n) on average: return len(set(lst)) != len(lst).
Exercise
A loop runs n times and calls max(lst) on a list of length n in each iteration. What is the total cost, and what is a simple fix if lst does not change inside the loop?
Show answer
Each max call is O(n), so the total is O(n^2). Compute m = max(lst) once before the loop. That costs O(n) once, and the whole thing becomes O(n).