Card 17: 2D Lists

Module 7: Expert Techniques

1 The Hook

A normal list is a line. A 2D List is a Grid.

Think of:

  • Spreadsheets (Rows & Columns)
  • Cinema Seats (Row A, Seat 5)
  • Game Maps (X, Y coordinates)

2 Worked Example

Accessing a Tic-Tac-Toe grid.

# A list OF lists
board = [
["X", "O", "X"], # Row 0
["O", "X", "O"], # Row 1
["X", "O", "X"]  # Row 2
]
# board[ROW][COL]
print(board[1][1]) # Prints Middle "X"

Changing the Grid

We can update a specific "cell" in the grid.

board = [ ["X", "O"], ["O", "X"] ]
board[0][1] = "WIN" # Change Row 0, Col 1
print(board) # [ ["X", "WIN"], ["O", "X"] ]

PREDICT

What gets printed?

temps = [
  [15, 20],
  [18, 22]
]
print(temps[1][0])

Remember: Row First, then Column. Start at 0.

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Tic Tac Toe

1. The board has an empty spot "-" at Row 1, Column 1.
2. Update that spot to be "X".
3. Print the board.

> _
SILVER (FIX)

🥈 Out of Bounds

1. We want to grab 99 from the grid.
2. The code tries `grid[0][2]`. BUT Row 0 only has index 0 and 1!
3. Fix the coordinates to find 99.

> _
GOLD (MAKE)

🥇 Vertical Maths

1. nums = [ [1, 10], [2, 20], [3, 30] ].
2. Goal: Sum the second column (Index 1) only.
3. Loop through every row.
4. Add row[1] to a total. (Should be 10+20+30 = 60).

> _
Previous: Algorithms Next: Validation