Python nested loops and matrices
Visit every cell of a rectangular matrix.
Python
matrix = [[1, 2, 3], [4, 5, 6]]
for row in matrix:
row_total = 0
for value in row:
row_total += value
print(row_total)Output
6 15
Explanation
A nested loop completes the inner loop for each outer iteration. A matrix can be represented as a list of rows, each of which is another list.
This example sums rows independently. Initializing row_total inside the outer loop is deliberate: each row needs a fresh total.
Explore the dry run
Guided walkthroughReady
1
matrix = [[1, 2, 3], [4, 5, 6]]2
for row in matrix:3
row_total = 04
for value in row:5
row_total += value6
print(row_total)Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create two rows of three values. | matrix = [[1, 2, 3], [4, 5, 6]] | — | |
| Begin the first row. | row = [1, 2, 3], row_total = 0 | — | |
| Add 1, then 2, then 3 in three inner iterations. | row_total: 1 -> 3 -> 6 | — | |
| Print the first row total. | row_total: 1 -> 3 -> 6 | 6 | |
| Reset for the second row. | row = [4, 5, 6], row_total = 0 | 6 | |
| Add 4, then 5, then 6 in three inner iterations. | row_total: 4 -> 9 -> 15 | 6 | |
| Print the second row total. | row_total: 4 -> 9 -> 15 | 6 15 |
Cost and common mistakes
O(r*c) time for r rows of c columns, O(1) auxiliary space excluding the matrix.
- Python's [[0] * 3] * 2 aliases the same inner list; use a comprehension for independent rows.
- An empty row prints 0; an empty matrix prints nothing.
Try it yourself
Predict the row totals after adding [7, 8, 9].
Reveal answer and reasoning
The output becomes 6, 15, and 24 on separate lines.