Nested Loops
A loop inside a loop: for every row, the inner loop runs all the way through. Build a 3 × 3 times table.
Python · beginner · 7 min · 33 steps · free
What you'll learn
- Follow the order of a nested loop
- Count how many times the inner body runs
- Build a list of lists
nested_loops.py
grid = []
for row in range(1, 4):
line = []
for col in range(1, 4):
line.append(row * col)
grid.append(line)
print(grid)
Step by step
- The table, as a list of rows.
row is created with the value 1.- A fresh, empty row for row 1.
col is created with the value 1.- Inner loop: row 1 × col 1 = 1.
col changes from 1 to 2.- 2 is added to the end of the list that
line points to. col changes from 2 to 3.- 3 is added to the end of the list that
line points to. - Python moves to the next item of the loop:
for col in range(1, 4). - The inner loop has finished all 3 columns; add the finished row.
- Next row. The inner loop starts again from col 1.
line now points to a different list: [].col changes from 3 to 1.- 2 is added to the end of the list that
line points to. col changes from 1 to 2.- 4 is added to the end of the list that
line points to. col changes from 2 to 3.- 6 is added to the end of the list that
line points to. - Python moves to the next item of the loop:
for col in range(1, 4). - a list is added to the end of the list that
grid points to. row changes from 2 to 3.line now points to a different list: [].col changes from 3 to 1.- 3 is added to the end of the list that
line points to. col changes from 1 to 2.- 6 is added to the end of the list that
line points to. col changes from 2 to 3.- 9 is added to the end of the list that
line points to. - Python moves to the next item of the loop:
for col in range(1, 4). - a list is added to the end of the list that
grid points to. - Python moves to the next item of the loop:
for row in range(1, 4). - A 3 × 3 times table: the outer loop chose the row, and the inner loop filled its columns.
Common mistakes
- Creating the inner list outside the outer loop, so every row is the same list
Best practices
- Keep nesting shallow; move deep inner loops into a function
Key takeaways
- The inner loop runs completely for every round of the outer loop.
- Total runs = outer count × inner count.
- Create per-row lists inside the outer loop.
Check yourself
Outer loop 4 rounds, inner loop 5 rounds. How many inner runs?
Answer: 20. 4 × 5 = 20.
Which loop finishes first in each round?
Answer: The inner loop. The inner loop completes before the outer loop moves on.
← break and continue · Lists: Adding, Removing and Sorting →
More in Control Flow