Sub topic 12
Hidden Loops in Built-in Operations
So far, every loop we counted was visible in the source code. Real programs also call built-in operations, and many of those operations contain loops of their own. A single line such as if x in items: can cost one step or a million steps, depending on what items is. This chapter shows how to find those hidden loops and include them in your step counts.
This chapter assumes you can read Python, count iterations of single and nested loops, and reduce a step count to Big-O and Big-Theta, as covered in earlier chapters.
Why a Line Is Not Always a Step
Earlier we defined a step as a constant-time basic operation, such as an arithmetic operation, a comparison, an assignment, or an index lookup like a[i]. The point of that definition was that each step costs a bounded amount of time, no matter how large the input is.
A built-in function call does not meet that definition automatically. len(items) on a list is constant time because Python stores the length. max(items) must look at every element, so it is a loop over n items written in C. The source code looks the same size in both cases, but the cost is very different.
When you count steps, ask the same question about every operation on a collection: does this operation have to touch many elements, or only a fixed number?
The Classic Example: Membership in a List
Here is a function that looks like a single loop:
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 result
def common_items_fast(a, b):
b_set = set(b) # one pass over b
return [x for x in a if x in b_set] # average O(1) lookups
print(common_items([1, 2, 3, 4], [3, 4, 5])) # [3, 4]
print(common_items_fast([1, 2, 3, 4], [3, 4, 5])) # [3, 4]Let n = len(a) and m = len(b). The visible loop runs n times. Inside it, x in b scans the list b from the front and compares x with each element until it finds a match. In the worst case, when x is not in b, that takes m comparisons. The hidden loop is nested inside the visible one, so the costs multiply:
common_items: worst case aboutn * mcomparisons, which isO(n * m). When both lists have lengthn, that isO(n^2).common_items_fast: building the set costsmsteps. Each of thenlookups costsO(1)on average. The total isO(n + m).
The fast version changes only the type of the container, but its order of growth is lower.
Making the Hidden Loop Visible
You can confirm that in on a list really loops by counting the equality comparisons it makes. The class below increments a counter every time Python calls its __eq__ method.
class Counted:
comparisons = 0
def __init__(self, value):
self.value = value
def __eq__(self, other):
Counted.comparisons += 1
return isinstance(other, Counted) and self.value == other.value
def __hash__(self):
return hash(self.value)
n = 1000
items = [Counted(i) for i in range(n)]
item_set = set(items)
Counted.comparisons = 0
print(Counted(-1) in items) # False
print(Counted.comparisons) # 1000: one comparison per element
Counted.comparisons = 0
print(Counted(n - 1) in items) # True
print(Counted.comparisons) # 1000: the match is the last element
Counted.comparisons = 0
print(Counted(0) in items) # True
print(Counted.comparisons) # 1: the match is the first element
Counted.comparisons = 0
print(Counted(n - 1) in item_set) # True
print(Counted.comparisons) # usually 1, independent of nThe list results match the early-exit analysis from the previous chapter. List membership is a linear search with a best case of 1 comparison and a worst case of n. The set lookup hashes the value and then compares against only the few entries that share that hash. The exact count can vary with hash collisions, but it does not grow with n.
A Reference Table of Common Costs
The table below lists typical costs for CPython's built-in types. Here n is the size of the container and k is the size of the slice or the other argument.
| Operation | Cost | Hidden loop? |
|---|---|---|
| `len(lst)`, `lst[i]`, `lst[i] = v` | O(1) | No |
| `lst.append(v)`, `lst.pop()` | O(1) amortized | No |
| `x in lst`, `lst.index(x)`, `lst.count(x)` | O(n) | Yes, a linear scan |
| `lst.remove(x)` | O(n) | Yes, a scan plus a shift |
| `lst.insert(0, v)`, `lst.pop(0)` | O(n) | Yes, every element shifts |
| `lst[a:b]` | O(k), with k = b - a | Yes, a copy |
| `lst.copy()`, `list(lst)`, `lst + other` | O(n) or O(n + k) | Yes, a copy |
| `min(lst)`, `max(lst)`, `sum(lst)` | O(n) | Yes |
| `sorted(lst)`, `lst.sort()` | O(n log n) | Yes, a full sort |
| `x in s` for a set, `d[key]` for a dict | O(1) average | No, on average |
| `set(lst)`, `dict.fromkeys(lst)` | O(n) | Yes, one insert per element |
| `"".join(parts)` | O(total length) | Yes, a single pass |
| `s1 == s2` for strings or lists | O(length) worst case | Yes |
| `deque.popleft()`, `deque.appendleft(v)` | O(1) | No |
Amortized O(1) means that most calls are cheap and an occasional call is expensive, for example when a list grows its storage. Averaged over many calls, each one costs a constant. For loop counting you can treat append as one step.
Common Traps
Removing from the Front of a List
A queue built on a list looks like a single loop:
from collections import deque
import timeit
def drain_list(n):
q = list(range(n))
while q:
q.pop(0) # shifts all remaining elements left
def drain_deque(n):
q = deque(range(n))
while q:
q.popleft() # constant time
for n in (10_000, 20_000, 40_000):
t_list = timeit.timeit(lambda: drain_list(n), number=1)
t_deque = timeit.timeit(lambda: drain_deque(n), number=1)
print(f"n={n:>6} list: {t_list:.4f}s deque: {t_deque:.4f}s")The while loop runs n times. On iteration i, pop(0) shifts the n - i - 1 remaining elements. The total is (n-1) + (n-2) + ... + 0 = n(n-1)/2, the same triangular sum from the dependent-loop chapter, so drain_list is Θ(n^2). When you run it, the list time should roughly quadruple each time n doubles. The deque time should roughly double. Exact timings depend on your machine. Because the element shifts happen in fast C code, the quadratic growth may only become obvious at larger n.
Slicing Inside a Loop
Slices copy their elements. This loop makes a new copy on every iteration:
def suffix_sums(nums):
result = []
for i in range(len(nums)):
result.append(sum(nums[i:])) # slice copies n - i items, sum reads them
return result
print(suffix_sums([1, 2, 3, 4])) # [10, 9, 7, 4]Iteration i copies n - i elements and then sums them. That gives 2(n + (n-1) + ... + 1) = n(n+1), which is Θ(n^2). A version with a running total, built by walking the list from right to left, is Θ(n):
def suffix_sums_fast(nums):
result = [0] * len(nums)
total = 0
for i in range(len(nums) - 1, -1, -1):
total += nums[i]
result[i] = total
return result
print(suffix_sums_fast([1, 2, 3, 4])) # [10, 9, 7, 4]Sorting or Searching Inside a Loop
Calling sorted, max, or min inside a loop multiplies the cost of the loop by the cost of the call. for x in a: if x == max(a): ... is Θ(n^2), because max(a) is recomputed on every iteration. If the value does not change, compute it once before the loop. That turns a multiplied cost into an added one: n + n instead of n * n.
Building Strings with +=
Strings are immutable, so in general s = s + piece creates a new string and copies all of s. Repeated in a loop, that copying adds up to Θ(n^2) in the total length. CPython sometimes optimizes s += piece to extend in place, but this is an implementation detail. It does not apply in other Python implementations and it fails when another reference to s exists. Collect the pieces in a list and call "".join(parts) once to get a guaranteed linear cost.
A Procedure for Counting with Built-ins
- Count the visible loops as usual.
- For each operation on a collection inside a loop, look up its cost in a table like the one above. Ask what it has to touch: one element, a slice, or the whole container.
- Treat a hidden O(f) operation inside a loop of
niterations exactly like a nested loop. Multiply if the size it touches stays fixed. Sum a series if the size changes with the loop variable. - Check whether an expensive call is loop-invariant, meaning its result does not change between iterations. If so, move it before the loop.
- Check whether a different container (a set, dict, or deque) offers the same operation in O(1).
Exercise
Give the worst-case order of growth of this function in terms of n = len(words), and explain where the hidden loop is. Then describe a change that makes it O(n) on average. def dedupe(words): seen = [] out = [] for w in words: if w not in seen: seen.append(w) out.append(w) return out
Show answer
The hidden loop is w not in seen, which scans the list seen. When all words are distinct, seen has length i on iteration i, so the total comparisons are 0 + 1 + ... + (n-1) = n(n-1)/2, which is Θ(n^2). (Assume each string comparison takes constant time, as with short words.) Making seen a set (seen = set() and seen.add(w)) makes each membership test O(1) on average, so the function becomes O(n). The list out stays a list to preserve order.
Exercise
A loop runs for i in range(n) and on each iteration calls sorted(data), where data has length n and does not change. What is the total cost, and how would you reduce it?
Show answer
Each call to sorted costs Θ(n log n), and it runs n times, so the total is Θ(n^2 log n). Since data does not change, the sort is loop-invariant. Sort once before the loop and reuse the result. The cost becomes Θ(n log n) for the sort plus Θ(n) for the loop, which is Θ(n log n) overall.
Exercise
Using the Counted class from this chapter, predict the number of comparisons made by Counted(500) in items when items = [Counted(i) for i in range(1000)]. Then predict the count for items.index(Counted(500)).
Show answer
Both perform a linear scan from the front and stop at the first match. The match is at index 500, so each makes 501 comparisons (indices 0 through 500).