Python Fundamentals · Control Flow

Nested Loops

A loop inside a loop: for every row, the inner loop runs all the way through. Build a 3 × 3 times table.

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

  1. The table, as a list of rows.
  2. row is created with the value 1.
  3. A fresh, empty row for row 1.
  4. col is created with the value 1.
  5. Inner loop: row 1 × col 1 = 1.
  6. col changes from 1 to 2.
  7. 2 is added to the end of the list that line points to.
  8. col changes from 2 to 3.
  9. 3 is added to the end of the list that line points to.
  10. Python moves to the next item of the loop: for col in range(1, 4).
  11. The inner loop has finished all 3 columns; add the finished row.
  12. Next row. The inner loop starts again from col 1.
  13. line now points to a different list: [].
  14. col changes from 3 to 1.
  15. 2 is added to the end of the list that line points to.
  16. col changes from 1 to 2.
  17. 4 is added to the end of the list that line points to.
  18. col changes from 2 to 3.
  19. 6 is added to the end of the list that line points to.
  20. Python moves to the next item of the loop: for col in range(1, 4).
  21. a list is added to the end of the list that grid points to.
  22. row changes from 2 to 3.
  23. line now points to a different list: [].
  24. col changes from 3 to 1.
  25. 3 is added to the end of the list that line points to.
  26. col changes from 1 to 2.
  27. 6 is added to the end of the list that line points to.
  28. col changes from 2 to 3.
  29. 9 is added to the end of the list that line points to.
  30. Python moves to the next item of the loop: for col in range(1, 4).
  31. a list is added to the end of the list that grid points to.
  32. Python moves to the next item of the loop: for row in range(1, 4).
  33. A 3 × 3 times table: the outer loop chose the row, and the inner loop filled its columns.