Nested lists: tables and matrices

Part of the free LogicWiz Python course, Module 5: Lists and tuples. The examples and practice run in the app.

Riya Ma'am keeps marks for 3 students in 3 subjects. She wants each student's total and each subject's total. One list per student, all inside one big list, does both.

You'll learn to

  • Store a table as a list of rows and reach any cell with `m[r][c]`
  • Loop over rows, and over columns with a nested loop
  • Add, transpose and multiply matrices, the university lab classics

Learn

A list of rows

A nested list is a list whose items are lists. Use it for any table:

marks = [[78, 85, 90],   # Aarav
         [66, 72, 58],   # Meher
         [88, 91, 95]]   # Riya
  • marks[1] is a whole row: Meher's [66, 72, 58].
  • marks[1][2] is row 1, column 2: Meher's third subject, 58.
  • len(marks) counts rows (3). len(marks[0]) counts columns (3).

Always read it as [row][column].

Reaching into the table

marks = [[78, 85, 90],
         [66, 72, 58],
         [88, 91, 95]]
print(marks[1])
print(marks[1][2])
marks[0][1] = 87
print(marks[0])
print(len(marks), len(marks[0]))

Row by row

names = ["Aarav", "Meher", "Riya"]
marks = [[78, 85, 90], [66, 72, 58], [88, 91, 95]]
for r in range(len(marks)):
    print(names[r], end=": ")
    for c in range(len(marks[r])):
        print(marks[r][c], end=" ")
    print("| total", sum(marks[r]))

end=" " keeps printing on the same line. The plain print(...) at the end of each row moves to the next line.

Column by column

marks = [[78, 85, 90], [66, 72, 58], [88, 91, 95]]
subjects = ["Maths", "Physics", "CS"]
for c in range(len(marks[0])):
    total = 0
    for r in range(len(marks)):
        total += marks[r][c]
    print(subjects[c], total)

For a column total, the outer loop picks the column and the inner loop walks down the rows.

Adding two matrices

a = [[1, 2], [3, 4]]
b = [[10, 20], [30, 40]]
result = []
for r in range(len(a)):
    row = []
    for c in range(len(a[0])):
        row.append(a[r][c] + b[r][c])
    result.append(row)
print(result)

Build each new row inside the loop, then append it. A fresh row each time, so no aliasing.

Transpose: rows become columns

m = [[1, 2, 3],
     [4, 5, 6]]
t = []
for c in range(len(m[0])):
    new_row = []
    for r in range(len(m)):
        new_row.append(m[r][c])
    t.append(new_row)
print(t)

A 2×3 matrix becomes 3×2. Column c of m becomes row c of t.

Mixing up m[r][c] and m[c][r] works on square tables and breaks on others, so always test with a non-square one like 2×3. And never build a table with [[0] * cols] * rows (Lesson 5.2): every row would be the same list.

AKTU, VTU, Anna and JNTU lab exams ask matrix addition, transpose and multiplication almost every semester. CBSE asks you to predict m[i][j] and len(m) for a nested list. Write the matrix programs as functions, then test them on a 2×3 matrix.

In one line

A table is a list of rows: m[r][c]; len(m) is rows, len(m[0]) is columns; build each new row inside the loop.