Nested For Loops

A loop inside a loop, the grid it walks, and why the work multiplies rather than adds.

Overview

The order things happen

for row in range(3):
    for col in range(4):
        print(row, col)

The outer loop takes row = 0 and then hands control to the inner loop, which runs all four of its passes before the outer loop moves to row = 1. Twelve lines print, in row-major order. The inner variable resets each time; the outer one does not.

This is the natural shape for anything two-dimensional: a grid, a table of rows and columns, every pairing of two lists.

nested.py

nested.py Python 3
Output

                    

nested_cost.py

nested_cost.py Python 3
Output

                    

Worth knowing

The inner loop finishes entirely on every single pass of the outer one.
Two nested loops over n items run n×n bodies. Doubling n quadruples the work; it does not double it.
break leaves only the loop it is in, the inner one. The outer loop carries on.
If both loops walk the same list, you are usually comparing every pair. That is often a sign a set or dict would do it in one pass.

Nested For Loops: A Practical Guide

A loop inside a loop runs the inner one from the top on every pass of the outer one. That is easy to say and easy to under-estimate: the bodies multiply, they do not add.

Where the newline goes

A detail that catches people: print() after the inner loop, indented to the outer loop, ends the row. Indent it one level further and you get a newline after every cell instead. The indentation is the logic here, not decoration.

The cost multiplies

One loop over n items runs n bodies. Two nested loops over n items run n×n. Put them side by side instead of inside each other and you get 2n. The difference between n² and 2n is the difference between a program that scales and one that does not:

  • n = 100: nested runs 10,000 bodies, sequential runs 200
  • n = 400: nested runs 160,000, sequential runs 800

Doubling the input quadruples nested work. The second program on this page times both at three sizes so the shape is visible rather than asserted.

break only leaves one loop

break exits the loop it is written in. Inside a nested pair, that is the inner loop; the outer one continues with its next pass. If you want out of both, the usual answers are to put the loops in a function and return, or to set a flag the outer loop checks.

When nesting is the wrong tool

If both loops walk the same collection, you are comparing every pair, and that is often avoidable. "Does any pair sum to the target?" looks like a natural nested loop and is a single pass with a set. Nesting is right when the two dimensions are genuinely independent — rows and columns, users and permissions — and suspicious when they are the same thing twice.

Check yourself

0 of 3

Answer without scrolling back up.

  1. Two loops nested over the same 500-item list. How many inner bodies run?

  2. A `break` in the inner loop of a nested pair does what?

  3. You double the size of the input to a doubly-nested loop. The work:

Cheat sheet

Nested For Loops

A loop inside a loop runs the inner one from the top on every pass of the outer one. That is easy to say and easy to under-estimate: the bodies multiply, they do not add.

PYTHON · vizlearn.in/python/nested_for_loops.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.