BeginnerCoder

Lesson 16 — Matrix traversal

Matrices: lists of lists

A matrix (grid) is a list of rows, and each row is a list of cells. m[r][c] is the cell in row r, column c. Nested loops visit every cell: the outer loop picks a row, the inner loop a column. Row sums are easy (sum(row)); column sums need the column index.

m = [[1, 2], [3, 4]]
m[1][0]                     # 3
sum(row[0] for row in m)    # 4 — the first column

Why it matters: spreadsheets, game boards and images (pixels) are all grids.

Want it another way?
Task

Fill in col_sums: for each column index c, the sum of row[c] over all rows.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Data Structures

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.