Course outline · 0% complete

0/32 lessons0%

Course overview →

Nested Loops

lesson 5-4 · ~10 min · 16/32

A loop inside a loop

Plenty of real data has two dimensions, rows and columns: an image is rows of pixels, a spreadsheet is rows of cells, a schedule is days by hours. To visit every cell you put a loop inside a loop. The outer loop picks a row, and for each single row the inner loop runs completely, visiting every column, before the outer loop moves to the next row.

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

The inner body runs 3 × 3 = 9 times. That multiplication is the key fact about nesting: total work is the product of the two loop sizes. It is also the standard reason a program is slow, a nested loop over two big collections multiplies into millions of passes, which is why interviewers probe it.

Code exercise · python

Run the multiplication grid. Watch the order: row 1 pairs with every col before row 2 starts, and the divider prints once per OUTER pass because it sits outside the inner loop.

Quiz

An outer loop runs 4 times, and its inner loop runs 5 times per outer pass. How many times does the inner body execute in total?

Code exercise · python

Your turn. Print a triangle of stars: 1 star on the first line, up to 4 on the last. You met string repetition in lesson 3-2, `"ab" * 3` is `"ababab"`, so each row is one multiplication, no inner loop needed when the language does the repetition for you.

Problem

Trace by hand. What single number does this print? ```python count = 0 for i in range(3): for j in range(i): count += 1 print(count) ```