2D Lists
1 2-Dimensional Lists (list of lists)
1.1 Create a grid/matrix
Consider a grid of 9 numbers arranged in 3 rows and 3 columns:
| Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
| Row 0 | 1 | 2 | 3 |
| Row 1 | 4 | 5 | 6 |
| Row 2 | 7 | 8 | 9 |
Lists are 1-dimensional, but we can create a 2-dimensional list by creating a list of lists. When making a 2D list, there are two valid approaches:
A grid is a list of rows
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
grid
│
├─ Row 0 ─► [1, 2, 3]
├─ Row 1 ─► [4, 5, 6]
└─ Row 2 ─► [7, 8, 9]
The value 8 is at index: [2][1] (row 2, column 1)
A grid is a list of columns
grid = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
grid
│
├─ Col 0 ─► [1, 4, 7]
├─ Col 1 ─► [2, 5, 8]
└─ Col 2 ─► [3, 6, 9]
The value 8 is at index: [1][2] (column 1, row 2)
Make the grid of 9 cells as shown above using either a “list of columns” or a “list of rows”, but fill it with zeros.
NoteHint
Create the grid first as a lis, and then add lists for each row or column.
TipSolution - as a list of rows
TipSolution - as a list of columns
Now, use a nested for loop to fill the grid with the numbers 1 through 9, and print the grid in a nice format.
TipSolution 1 - traverse the grid and fill values
TipSolution 2 - traverse the grid and fill values