Learn Python
>>> control_flow.nested_loops

Nested Loops in Python

#concept

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.

#how it works
1

Write an outer loop

A for or while loop, as usual.

2

Indent a second loop inside it

One level further, inside the outer loop’s body.

3

The inner loop runs fully each time

For every single iteration of the outer loop, the entire inner loop runs start to finish.

4

break and continue act on the nearest loop only

Each independently affects just the loop it’s directly inside.

5

Total inner executions multiply

Outer count × inner count, not outer count + inner count.

#example
for row in range(2):
for col in range(3):
print(f"({row}, {col})")
Output
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
1The outer loop starts with row = 0, then runs the entire inner loop, printing (0, 0), (0, 1), and (0, 2) in turn.
2Once the inner loop is exhausted, the outer loop moves to row = 1, and the inner loop runs again from scratch, printing (1, 0), (1, 1), (1, 2).
3In total, the inner print() runs 2 × 3 = 6 times, matching the six lines of output.
#complexity
time O(n × m)
space O(1)

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.

#use cases
Working with grids, matrices, or any two-dimensional data, like a tic-tac-toe board
Comparing every item in one list against every item in another
Generating combinations, like every possible pairing between two small sets
Printing tabular or chart-like output, row by row and column by column

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.