11-nested-loops.py
python-for-j277 / data-structures  ·  Lesson 11
Lesson 11 — Data structures

Nested Loops

A loop inside a loop — perfect for grids.

A nested loop is a loop placed inside another loop. The inner loop runs fully for every single pass of the outer loop. They are ideal for working through a 2-D array.

How a nested loop runs

nested.py
for row in range(3):
    for col in range(2):
        print("row", row, "col", col)
Output
row 0 col 0
row 0 col 1
row 1 col 0
row 1 col 1
row 2 col 0
row 2 col 1
How it works
  • The outer loop runs 3 times (row = 0, 1, 2).
  • For each of those, the inner loop runs fully (col = 0, 1).
  • That gives 3 × 2 = 6 lines in total.

Building a pattern

stars.py
for row in range(3):
    for star in range(5):
        print("*", end="")
    print()
Output
*****
*****
*****
How it works
  • The inner loop prints 5 stars on the same line — end="" stops print() starting a new line.
  • The empty print() after the inner loop moves down to the next line.
  • The outer loop repeats this for 3 rows.

Walking through a 2-D array

walk.py
grid = [
    [1, 2, 3],
    [4, 5, 6]
]
for row in grid:
    for value in row:
        print(value, end=" ")
    print()
Output
1 2 3 
4 5 6 
How it works
  • The outer loop takes each row of the grid.
  • The inner loop takes each value within that row.
  • This visits every cell, row by row.
Inner finishes firstThe inner loop completes all of its passes for each single pass of the outer loop.

What you have learned

  • A nested loop is a loop inside another loop.
  • The inner loop runs in full on every pass of the outer loop.
  • Total passes = outer count × inner count.
  • Nested loops are the natural way to process a 2-D array.