Matrices: indexing, row and column sums

Beginner Python for Data Science
Created by Best · 24.06.2026 at 14:03 UTC

Real data is usually two-dimensional: a grid of rows and columns. A spreadsheet, a feature table, a grayscale image — all are matrices, and in plain Python a matrix is a list whose elements are themselves lists. Each inner list is one row:

M = [[1, 2, 3],
     [4, 5, 6]]

To reach a single cell you index twice — row first, then column — the same convention mathematics uses:

print(M[0][2])   # row 0, column 2 -> 3
print(M[1][0])   # row 1, column 0 -> 4

Two dimensions mean two loops, one inside the other. Summing each row is a loop over rows, where each row is itself something you can sum:

for row in M:
    print(sum(row))      # 6, then 15

Summing each column is subtler, because a column runs across the rows. You hold a column index fixed and loop down the rows:

ncols = len(M[0])
for c in range(ncols):
    col_total = 0
    for r in range(len(M)):
        col_total += M[r][c]
    print(col_total)     # 5, 7, 9

That outer-then-inner nested loop is the grammar of all 2-D work.
leads into “Transpose and the ragged-row pitfalls”.*

University approvals: 0
Related cards
Builds on Why loops first, and the length pitfall · Python for Data Science
Next Transpose and the ragged-row pitfalls · Python for Data Science
Tasks
Question 1

For M = [[1, 2, 3], [4, 5, 6]], what is M[1][0]?

Question 2

stdin gives a matrix: first line R C (rows, cols), then R lines of C space-separated ints. Print the sum of each row, one per line.

Example input:

2 3
1 2 3
4 5 6

Expected output:

6
15
3 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Python for Data Science
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy