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
Tasks
Card Info
- Topic: Python for Data Science
- Difficulty: Beginner
- Completed: 0 users
Creator
Best
BestBuddy