Python 3D Academyবাংলা

Lists of lists

🌍 In real life. A cinema's seat map has rows, and each row has seats: "row C, seat 5". A class marks sheet has one row per student, and each row has a mark for each subject. To find one value, you give two positions: which row, then which place in that row.

In Python, that's a list of lists.

The idea in one sentence: a list can hold other lists, so grid[r] is a whole row and grid[r][c] is the item in row r, column c.

Its words:

  • nested list: a list whose items are lists
  • row: one inner list; column: the same position in every row
  • grid: a nested list where every row has the same length

Step by step, for grid[1][2] when grid is [[1, 2, 3], [4, 5, 6]]:

  1. grid[1] picks the second row: [4, 5, 6].
  2. [2] picks index 2 of that row: 6.
grid = [[1, 2, 3],
        [4, 5, 6]]
print(grid[1])
print(grid[1][2])
print(len(grid), "rows")
Inside brackets, Python lets you break a long line like this.

To visit every item, use a loop inside a loop: the outer loop takes each row, and the inner loop takes each item in that row.

grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
    for x in row:
        print(x, end=" ")
    print()

Often you only need one loop, because sum(), max() and len() work on a whole row at once:

marks = [[7, 9, 8], [5, 6, 10], [9, 9, 9]]
for row in marks:
    print(row, "total:", sum(row))

What it costs. Reaching one cell, grid[r][c], is two instant jumps. Visiting every cell takes rows × columns laps: a 100 × 100 board has 10,000 cells.

Mistakes and edge cases.

  • Commas inside one pair of brackets. grid[1, 2] gives TypeError: list indices must be integers or slices, not tuple. Write grid[1][2].
  • A row index past the end. With 2 rows, grid[2] gives IndexError: list index out of range.
  • Rows of different lengths. A loop that assumes 3 columns breaks on a shorter row. Loop over each row's own items.
  • Making a board with *. [[0] * 3] * 2 puts the same row in twice, so changing one changes both (see below; Chapter 13 explains why). Build each row separately with append.
board = [[0] * 3] * 2
board[0][0] = 1
print(board)

safe = []
for r in range(2):
    safe.append([0] * 3)
safe[0][0] = 1
print(safe)
The first board's two rows are one and the same list, so both show the 1. The safe board makes a new row on each lap.

Quiz

  1. What does this print?

    g = [[1, 2], [3, 4]]
    print(g[1][0])
  2. What does this print?

    g = [[1, 2], [3, 4], [5, 6]]
    print(len(g), len(g[0]))
  3. What does this print?

    g = [[1, 2], [3, 4]]
    total = 0
    for row in g:
        for x in row:
            total += x
    print(total)
  4. In board = [["X", "O"], ["O", "X"]], how do you get the bottom-right item?

    • board[1][1]
    • board[2][2]
    • board[1, 1]
  5. Which line has a mistake?

    g = [[1, 2], [3, 4]]
    print(g[0][2])

Coding tasks

  1. Here is a grid: grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Print the middle item, then the bottom-right item.

  2. Ask for a number of rows n. Then read n lines; each line has whole numbers separated by spaces. Print the total of each row, one per line.

  3. Each customer has money in a few banks: accounts = [[1, 5], [7, 3], [3, 5]]. A customer's wealth is the total of their row. Print the wealth of the richest customer.