📋 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].
Tic-tac-toe board
Who wins? Check board[0][0], board[1][1] and board[2][2].
Grade book
Add a row for yourself. row[1:] slices off the name, leaving just the marks.
What does this print?
The shared-row trap
In bad, changing one row changed all three.
One row, three references
[[0] * 3] * 3 builds one row [0, 0, 0], then an outer list holding three references to that same row.
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).
Deep copy
deep copied the rows too, so the 99 doesn't reach it.
Use deepcopy when the list holds lists.
What does this print?
Sales table
Each row of sales is a day; each column is a
product.
- Append each day's total to
day_totals. - Add each number to its product's slot in
product_totals(column 0, 1 or 2).