Python · Course navigation

Python nested loops and matrices

Visit every cell of a rectangular matrix.

On this page
Before you start

Lists, indexing, and for loops.

  • Visit every cell of a rectangular matrix.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1matrix = [[1, 2, 3], [4, 5, 6]]
2for row in matrix:
3 row_total = 0
4 for value in row:
5 row_total += value
6 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

Behind the scenes

How Python processes this code

Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.

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.

Further reading