Nested Loops
Python · Loops
Theory
A nested loop is a loop inside the body of another loop. For every single pass of the outer loop, the inner loop runs completely from start to finish. In the example the outer loop takes i = 0, and the inner loop prints (0, 0) and (0, 1); then the outer loop takes i = 1 and the inner loop starts over from j = 0. The total number of inner passes is the outer count times the inner count: 2 x 2 = 4 here.
That multiplication is the key performance point. Two nested loops over n items each do n x n work, O(n squared): 1,000 items means a million inner passes, and a third level makes it a billion. A common example is comparing every item with every other item to find duplicates, which a set can do in a single pass. Also remember that break only exits the innermost loop it is in; to stop both loops, use a flag variable, put the loops in a function and return, or restructure with itertools.product.
Why we use it
Some problems are naturally two-dimensional: rows and columns of a grid, every pair of products, each store times each month. Nested loops visit every combination.
When to use it
Use nested loops for grids, matrices and small pairwise comparisons. For large data, look for a faster approach: a set or dict lookup instead of an inner search loop, itertools.product for combinations, or vectorised pandas/NumPy operations.
How it works
- Outer loop takes the next i
- Inner loop restarts at j = 0
- Run the inner body: print(i, j)
- More j values? Yes: Next j, run the body again. No: Inner loop finished.
- More i values? Yes: Back to the outer loop. No: Both loops done.
- Total passes = outer count x inner count
Syntax
for x in outer:
for y in inner:
...Example
for i in range(2):
for j in range(2):
print(i, j)Key points
- The inner loop completes fully for each outer iteration
- Total passes = outer count x inner count
- Watch performance: nested loops multiply the iteration count, often O(n^2)
- break exits only the innermost loop
- Replace an inner search loop with a set or dict lookup when possible