loop
Lists in advanced applications

Module 3 · Lists in advanced applications · Lesson 2 of 3

Two-dimensional arrays

Put lists inside a list and you get a two-dimensional array — a grid. Think of the outer list as the rows, and each inner list as the cells across one row. A chessboard, a spreadsheet, a game of tic-tac-toe: all of them are just a list of rows.

Reading a cell is a two-step move: grid[1] picks the row, then [2] picks the column within it. Watch the two steps happen.

grid[1][2]
0123
01234
15678
29101112

So grid[row][col] — row first, then column. Assigning works the same way: grid[1][2] = 99 changes exactly one cell.

Run it yourselfruns in your browser · Python
main.py

You rarely type a grid out by hand. A nested comprehension builds one at any size, and two nested for loops are the natural way to walk every cell.

Run it yourselfruns in your browser · Python
main.py

One trap to remember from the references lesson: [[0] * 3] * 2 does not make two rows — it makes two references to the same row, so editing one edits both. The comprehension gives each row its own list. Run this to see the difference.

Run it yourselfruns in your browser · Python
main.py