Interactive Guide to Python

Grids & Matrices

Multi-Dimensional Data • Game Boards • Spreadsheet-Like Structures

🧠 Mental Model: Digital Spreadsheet

Think of 2D lists like a digital spreadsheet:

  • 🗂️ Rows - Each outer list element is a row (horizontal)
  • 📊 Columns - Each inner list element is a column (vertical)
  • 🎯 Coordinates - Access cells using [row][column] indexing
  • 📝 Grid Data - Perfect for game boards, tables, matrices

Step 1: Understanding 2D Structure

A 2D list is essentially a list containing other lists. Each inner list represents a row, and the elements within each row represent columns. It's like having a table or grid in code.

Visual Example: 3x4 Grid

1
2
3
4
5
6
7
8
9
10
11
12
# This grid represents:
grid = [
    [1, 2, 3, 4],    # Row 0
    [5, 6, 7, 8],    # Row 1
    [9, 10, 11, 12]  # Row 2
]

# Access elements using grid[row][column]
print(grid[0][1])  # Output: 2
print(grid[1][2])  # Output: 7
print(grid[2][3])  # Output: 12

Step 2: Creating 2D Lists

Method 1: Direct Creation

# Create a tic-tac-toe board
board = [
    ['X', 'O', ' '],
    ['O', 'X', ' '],
    [' ', ' ', 'X']
]

# Print the board
for row in board:
    print(row)

Method 2: Using List Comprehension

# Create a 3x3 grid filled with zeros
rows, cols = 3, 3
grid = [[0 for _ in range(cols)] for _ in range(rows)]

# Result: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
print(grid)

⚠️ Critical Pitfall: Shallow Copy Trap

NEVER create 2D lists like this:

# ❌ WRONG - Creates references to the same inner list
row = [0, 0, 0]
grid = [row] * 3  # All rows point to the same list!

# When you modify one cell, ALL rows change!
grid[0][0] = 1
print(grid)  # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] - OOPS!

This is the same "name tag" concept from our lists lesson - multiple name tags pointing to the same object!

Step 3: Interactive Grid Builder

🎮 Try it: Build Your Own Grid

Step 4: Real-World Applications

🎮 Game Development

Chess boards, tic-tac-toe, Sudoku, maze navigation, tile-based games

📊 Data Analysis

Spreadsheet data, statistical matrices, data tables, CSV processing

🖼️ Image Processing

Pixel grids, image filters, computer vision, graphics processing

🧮 Mathematics

Matrix operations, linear algebra, scientific computing, simulations