Menu

Count Controlled Iteration (For Loops)

Nested for Loops

A nested loop is a for loop written inside the body of another for loop. The outer loop controls the larger job and the inner loop carries out a smaller job for each step of it. The inner loop completes all of its repetitions before the outer loop moves on to its next repetition, so the two loops never run side by side.

How the repetitions multiply

If the outer loop repeats 3 times and the inner loop repeats 5 times, the inner loop's body runs 3 × 5 = 15 times. Following the loop variables makes this easy to see: the outer loop variable stays fixed while the inner loop variable counts all the way through, then it starts again from its first value.

Outer loop variableInner loop variable countsInner loop body runs
11, 2, 3, 4, 55 times
21, 2, 3, 4, 55 times
31, 2, 3, 4, 55 times

In the program below the outer loop picks a row of the hall and the inner loop visits each seat in that row, so every seat is labelled exactly once.

An inner for loop box inside an outer for loop box, beside a 3 by 5 grid of seats numbered 1 to 15 in the order printed, showing each row finishes before the next starts.

# Labels every seat in a hall with 3 rows of 5 seats
for row in range(1, 4):
    for seat in range(1, 6):
        print("Row " + str(row) + " seat " + str(seat))

Output:

Row 1 seat 1
Row 1 seat 2
Row 1 seat 3
Row 1 seat 4
Row 1 seat 5
Row 2 seat 1
Row 2 seat 2
Row 2 seat 3
Row 2 seat 4
Row 2 seat 5
Row 3 seat 1
Row 3 seat 2
Row 3 seat 3
Row 3 seat 4
Row 3 seat 5

Records and fields in a two-dimensional structure

A two-dimensional data structure stores data in rows and columns, like a table. In a table of records, each row is one record and each column is a field. Nested loops are ideal for this because they can process every field in every record: the outer loop traverses the records, working down the table one row at a time, and the inner loop traverses the fields in that record, working across the row. Because the inner loop restarts for each new record, every field in that record is processed before moving to the next record.

Practise this