10-2d-arrays.py
python-for-j277 / data-structures  ·  Lesson 10
Lesson 10 — Data structures

2-D Arrays

A grid of values — a list of lists.

A two-dimensional array stores values in a grid of rows and columns, like a seating plan or a spreadsheet. In Python it is a list of lists.

Building a grid

grid.py
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(grid[0])
Output
[1, 2, 3]
How it works
  • Each inner list is one row of the grid.
  • grid[0] gives the whole first row.
  • The outer list holds the rows in order.

Reaching a single cell

cell.py
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(grid[0][2])
print(grid[2][0])
Output
3
7
How it works
  • The first index picks the row; the second index picks the column.
  • grid[0][2] is row 0, column 2 — the value 3.
  • grid[2][0] is row 2, column 0 — the value 7.
  • Both indexes start at 0.

Changing a cell

update.py
seats = [
    ["free", "taken"],
    ["free", "free"]
]
seats[0][0] = "taken"
print(seats)
Output
[['taken', 'taken'], ['free', 'free']]
How it works
  • seats[0][0] selects row 0, column 0.
  • Assigning to it replaces just that one cell.
Row first, then columnThink of it as [row][column], in that order, every single time.
A grid of valuesA 2-D array is a list of rows; use two indexes to reach one cell.

What you have learned

  • A 2-D array is a list of lists, arranged as rows and columns.
  • One index gives a whole row; two indexes give a single cell.
  • The order is always [row][column].
  • Both indexes start at 0.