Sub topic 1
What Counts as a Step
Before you can count the steps of a loop, you need a definition of "step" that holds still. This chapter sets up the cost model used in the rest of the tutorial. It explains what a step is, which Python operations qualify as one, and why we count steps instead of measuring seconds.
Prerequisites
This chapter assumes you can already:
- Read and write basic Python, including functions, lists, and dictionaries.
- Follow
forandwhileloops and say what values the loop variable takes. - Work with basic algebra, including exponents such as n² and 2ᵏ.
- Recognize a logarithm such as log₂ n. You will not need logarithms until later chapters.
No calculus or formal proof technique is needed.
Why Not Just Time the Code?
The obvious way to learn how fast a program runs is to run it and look at a clock. That is useful for tuning a real system. It is a poor way to reason about an algorithm, for four reasons.
- Hardware differs. The same function runs at different speeds on a laptop, a phone, and a server.
- Software differs. The Python version, the interpreter (CPython or PyPy), and the operating system all change the timings.
- Noise is constant. Other processes, CPU frequency scaling, caching, and garbage collection make two runs of the same code give different times.
- A timing describes one input. A measurement at n = 10,000 tells you little about n = 10,000,000 unless you already know how the cost grows.
The script below times a simple loop at three input sizes. Run it twice and you will get different numbers. Run it on another machine and the numbers change again.
import timeit
def touch_all(items):
for x in items:
pass
for n in (10_000, 20_000, 40_000):
data = list(range(n))
seconds = timeit.timeit(lambda: touch_all(data), number=200)
print(f"n={n:>6} time={seconds:.4f}s")The absolute times are not stable, but one thing usually is. Each time n doubles, the time roughly doubles. That ratio comes from the structure of the code, the fact that the loop body runs once per item. Step counting captures that structure directly, without the noise.
The Definition: A Step Is a Constant-Time Operation
A step is any operation whose cost does not depend on the size of the input. The operation may take 1 nanosecond or 50 nanoseconds. What matters is that its cost is bounded by some fixed constant, whether the input has 10 items or 10 million.
This is the idea behind the RAM model (random-access machine) that algorithm textbooks use. In that model:
- Each simple operation costs one unit.
- Memory access by address costs one unit, regardless of which address.
- Operations run one after another.
The model is deliberately simplified. Real CPUs have caches, pipelines, and parallel execution units. The simplification works because those effects change the cost by a constant factor, and constant factors are exactly what later chapters drop when moving to Big-O notation.
Why the Exact Constant Does Not Matter
Consider this function:
def average_of_three(a, b, c):
total = a + b + c
return total / 3
print(average_of_three(4, 8, 9)) # 7.0You could count two additions, one assignment, one division, and one return, which gives 5 steps. Someone else might count the two argument lookups for a + b separately and get 7. Both counts are defensible, and the disagreement does not matter. Either way the function does a fixed amount of work that never grows. We call that constant cost and write it as O(1).
Choosing a cost of exactly 1 for each operation is a convenience. Any fixed positive cost per operation would produce the same order of growth. That is why you can count loosely inside a loop body and still get the right answer about how the program scales.
Which Python Operations Are One Step?
The definition is simple. Applying it to Python takes some care, because some operations that look like one step are really loops. The table lists common operations with their typical cost in CPython.
| Operation | Example | Constant time? | Notes |
|---|---|---|---|
| Arithmetic on small numbers | `x + 1`, `x * y`, `x // 2` | Yes | Assumes the numbers fit in a machine word |
| Comparison of numbers | `x < y`, `x == 0` | Yes | |
| Assignment | `total = 0` | Yes | Binds a name; no data is copied |
| List indexing | `items[i]`, `items[i] = v` | Yes | Lists are arrays with direct addressing |
| `len()` of a list, str, dict | `len(items)` | Yes | The length is stored, not recomputed |
| Append to a list | `items.append(v)` | Yes (amortized) | An occasional resize is spread over many appends |
| Dict or set lookup | `d[key]`, `key in s` | Yes (average) | Worst case is linear, but rare in practice |
| Membership in a list | `v in items` | **No** | Scans the list: up to `len(items)` steps |
| Slicing | `items[a:b]` | **No** | Copies `b - a` elements |
| Insert at the front | `items.insert(0, v)` | **No** | Shifts every element |
| Built-in reducers | `sum(items)`, `max(items)` | **No** | Loop over every element |
| Sorting | `sorted(items)` | **No** | About n log n comparisons |
The rows marked No contain loops inside them. A later chapter, "Hidden Loops in Built-in Operations," covers how to count them. For now, remember the rule: an operation is a step only if its cost stays fixed as the data it touches grows.
The diagram shows how to decide.
Gotchas in the Cost Model
Big Integers Are Not Fixed Size
Python integers have arbitrary precision. Adding two 20-digit numbers is effectively constant time. Multiplying two numbers with a million digits each is not, because the work grows with the number of digits. The usual convention is to treat arithmetic as one step when values stay within a reasonable range, such as array indices, counters, or sums of small values. If your algorithm builds huge numbers, such as computing a large factorial, the convention no longer holds.
import time
for digits in (10_000, 100_000, 1_000_000):
x = 10 ** digits - 1
start = time.perf_counter()
_ = x * x
elapsed = time.perf_counter() - start
print(f"{digits:>9} digits: {elapsed:.5f}s")The time per multiplication rises steeply as the digit count grows. Here a single * stops being a single step.
Strings Are Immutable
s = s + "x" builds a brand-new string and copies every character of s into it. In a loop that runs n times, this can add up to roughly n²/2 character copies. CPython sometimes optimizes this case in place, but you should not rely on that. "".join(parts) is the reliably linear alternative.
Function Calls Cost What Their Bodies Cost
A call such as process(item) is one step only if process itself does constant work. When it contains a loop, you count its steps and then multiply by the number of calls. Treat every call as a question to answer, never as a free step.
Average Versus Worst Case for Hashing
Dictionary and set lookups cost O(1) on average. With adversarial keys that all collide, a lookup can degrade to a linear scan. This tutorial uses the average-case cost unless it says otherwise, as most practitioners do.
Counting Steps in Practice
Here is a short function with the step count written beside each line. The counting granularity is one step per simple operation.
def first_and_last_sum(items):
if len(items) == 0: # len: 1, compare: 1
return 0 # 1 (only if empty)
first = items[0] # index + assign: 2
last = items[-1] # index + assign: 2
return first + last # add + return: 2
print(first_and_last_sum([3, 1, 4, 1, 5])) # 8
print(first_and_last_sum([])) # 0A non-empty list costs 8 steps whether it has 5 items or 5 million. An empty list costs 3. Both are constants, so the function is O(1). Notice that no line touches more than a fixed number of elements. That is the property to look for.
Compare this version:
def first_and_total(items):
first = items[0] # 2 steps
total = sum(items) # hidden loop: about len(items) steps
return first + total # 2 steps
print(first_and_total([3, 1, 4, 1, 5])) # 17There is no for keyword anywhere, but sum visits every element. Its cost is about n + 4 steps for a list of length n, so it grows linearly. The next chapter shows how to count loops you write yourself, and later chapters return to loops hidden inside calls like this one.
Common Errors
- Counting seconds instead of steps. Timings mix the algorithm with the machine. Count operations first, then measure if you need to.
- Arguing over the exact constant. Whether a line is 2 steps or 3 rarely matters. What matters is whether the count grows with n.
- Treating every line as one step. A line with
inon a list, a slice,sum, orsortedcontains a loop. - Forgetting that a function call has a body. Look inside, or look up the documented cost.
- Assuming arithmetic is always constant. That holds for word-sized numbers. Huge integers break it.
Exercise
Which of these lines are a single constant-time step when items is a Python list of length n and d is a dict? (a) x = items[n // 2] (b) found = 7 in items (c) d["key"] = len(items) (d) tail = items[1:]
Show answer
(a) and (c) are constant time. Indexing a list and computing len are O(1), and dict assignment is O(1) on average. (b) scans the list, up to n comparisons. (d) copies n - 1 elements into a new list. Both (b) and (d) grow with n.
Exercise
A colleague times a function at n = 1,000 and gets 2 ms on their laptop. You get 0.5 ms on your workstation. Does this tell you the function scales differently on the two machines? What would you do to compare how it scales?
Show answer
No. A single timing reflects hardware, interpreter, and noise as well as the algorithm, so a 4x gap is just a constant-factor difference between the machines. To compare scaling, count the steps as a function of n, or time each machine at several sizes (for example n = 1,000, 2,000, 4,000) and compare how the time grows from one size to the next, not the absolute values.
Exercise
Count the steps of def f(x, y): z = x * y; return z - 1 using one step per arithmetic operation, assignment, and return. Is it O(1) for all integer inputs?
Show answer
There are 4 steps: multiply, assign, subtract, return. It is O(1) when x and y fit in a machine word, which is the usual convention. For very large Python integers the multiplication cost grows with the number of digits, so it is not constant for arbitrarily large inputs.