Lesson 3.8 – Introduction to 2D Lists

What we’ll learn today

  • What a 2D list is
  • How to create and access elements in a 2D list
  • Looping through 2D lists

Quick Review

  • How do you access the 3rd element in a 1D list?
  • How are lists and tuples different?

What is a 2D List?

  • A list of lists (like a table or grid)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

Accessing Elements

  • Use two indexes: row, then column
print(matrix[0][1])   # 2
print(matrix[2][2])   # 9

Changing Elements

matrix[1][1] = 99
print(matrix)

Looping Through Rows

for row in matrix:
    print(row)

Looping Through All Elements

for row in matrix:
    for val in row:
        print(val)

Class Question

  • How could a 2D list be useful in a game?

Mini Practice

  1. Create a 2D list representing a tic-tac-toe board:
board = [
    ["X", "O", "X"],
    [" ", "X", "O"],
    ["O", " ", " "]
]
  1. Print the middle element.
  2. Change the bottom-right element to "X".

Mini Challenge

  • Write a program that:
    1. Creates a 3x3 grid of numbers 1–9
    2. Prints the grid row by row