TwiddleLab / Code / Build with Python
Grids: Lists of Lists
What you will learn
- A grid is a list of lists: board[1] is a whole row, board[1][2] one cell.
- Row first, then column: board[r][c].
- On a board the row number goes down; on a math plane y goes up. Same numbers, different places.
- Nested loops visit every cell: for r, then for c.
How the lesson goes
X just won. How does a program know?
First, you: tap the three cells of the winning line.
Which cell is board[2][0]?
The board is a list of three lists. Pin your guess.
Step through it.
First the three lists stack up. Then each lookup lights a row, then a cell.
Lists of lists.
A list of lists stores a grid: each inner list is one row.
board[r] is a whole row; board[r][c] is one cell: row first, then column.
board[r][c] = "O" changes one cell. Nested loops, for r and then for c, visit every cell.
Play these four lines on the board.
For each line, drag X or O onto the cell it sets.
Build a row checker.
It should print the winner of any full row, or none. Three test boards.
board[1][2] and the point (1, 2): same numbers. Same place?
Light each one, then tap the picture where the first number moves you down.
This column check misses an obvious win.
Column 0 is all X. Run it, then fix the lookup that reads the wrong cell.
Minesweeper: find the 4 mines.
Each number counts mines in the 8 cells around it. Dig safe cells, flag the mines.
Your move. Your checker decides.
Tap a cell to play X. Your row checker from earlier runs on the new board.
Previous lesson: Randomness and Simulation · Next lesson: Tic-Tac-Toe with a Bot · Part of the course: Build with Python
Lessons are interactive and need JavaScript. Turn it on to play them.