Nested Loops in Python
A nested loop is a loop written inside another loop's body. The inner loop runs to completion for every single iteration of the outer loop — so a 3-iteration outer loop containing a 4-iteration inner loop runs the inner block 12 times in total, not 7.
Write an outer loop
A for or while loop, as usual.
Indent a second loop inside it
One level further, inside the outer loop’s body.
The inner loop runs fully each time
For every single iteration of the outer loop, the entire inner loop runs start to finish.
break and continue act on the nearest loop only
Each independently affects just the loop it’s directly inside.
Total inner executions multiply
Outer count × inner count, not outer count + inner count.
for row in range(2): for col in range(3): print(f"({row}, {col})")For an outer loop of length n and an inner loop of length m, the inner body runs n × m times total. When both loops run over the same collection of size n — common when comparing every pair of items — this becomes O(n²): doubling the input size roughly quadruples the work, which is why nested loops over large collections are often the first thing worth optimizing.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.