Lists of lists

Lists & Tuples, lesson 5 of 6

📋 Lists & Tuples, lesson 5 of 6

Lists of lists

Model grids, boards and tables with nested lists.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A list can hold other lists. That's perfect for grids and tables: each inner list is a row. Use two indexes, row first: grid[row][col].

Example

Tic-tac-toe board

Who wins? Check board[0][0], board[1][1] and board[2][2].

Example

Grade book

Add a row for yourself. row[1:] slices off the name, leaving just the marks.

Quiz

What does this print?

Example

The shared-row trap

In bad, changing one row changed all three.

Walkthrough

One row, three references

badlist012list000102
Step 1 of 4

[[0] * 3] * 3 builds one row [0, 0, 0], then an outer list holding three references to that same row.

shared row
own row
Example

Copies are shallow

.copy() (and [:]) copies only the outer list: twin is a new list, but it holds the same rows as grid. Appending to twin leaves grid alone, while changing a shared row shows up in both. To copy the rows too, start with safe = [] and loop: safe.append(row.copy()) for each row.

To copy the rows too, use copy.deepcopy(). It lives in the copy module: import copy loads that module of ready-made tools (you'll learn about imports later).

Example

Deep copy

deep copied the rows too, so the 99 doesn't reach it. Use deepcopy when the list holds lists.

Quiz

What does this print?

Exercise

Sales table

Each row of sales is a day; each column is a product.

  1. Append each day's total to day_totals.
  2. Add each number to its product's slot in product_totals (column 0, 1 or 2).