2D Arrays & Matrices
A 2D array is a list of lists — like a table with rows and columns. They represent grids, matrices, game boards, spreadsheets, and any data organized in rows and columns.
Learning Objectives
- 11.4.3.1 Use two-dimensional arrays to solve problems
Conceptual Anchor
The Spreadsheet Analogy
A 2D array is a spreadsheet: rows are individual lists, columns are elements at
the same position. Access a cell by its row and column:
grid[row][col].
Rules & Theory
Creating 2D Arrays
# Direct creation
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Access: matrix[row][col]
print(matrix[0][0]) # 1 (row 0, col 0)
print(matrix[1][2]) # 6 (row 1, col 2)
print(matrix[2][1]) # 8 (row 2, col 1)
# Creating with loops
rows, cols = 3, 4
grid = []
for i in range(rows):
grid.append([0] * cols)
# [[0,0,0,0], [0,0,0,0], [0,0,0,0]]
# List comprehension
grid = [[0] * cols for _ in range(rows)]
# ⚠ WRONG WAY (shared references!)
# bad = [[0] * cols] * rows # All rows point to same list!Traversing 2D Arrays
matrix = [[1,2,3], [4,5,6], [7,8,9]]
# Row by row
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each row
# With indices
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f"[{i}][{j}]={matrix[i][j]}", end=" ")
print()
# Row info
print("Rows:", len(matrix)) # 3
print("Cols:", len(matrix[0])) # 3Worked Examples
1 Row & Column Sums
matrix = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# Row sums
for i, row in enumerate(matrix):
print(f"Row {i} sum: {sum(row)}")
# Column sums
cols = len(matrix[0])
for j in range(cols):
col_sum = sum(matrix[i][j] for i in range(len(matrix)))
print(f"Col {j} sum: {col_sum}")2 Matrix Addition
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
rows = len(A)
cols = len(A[0])
C = [[0]*cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
C[i][j] = A[i][j] + B[i][j]
# C = [[6, 8], [10, 12]]
for row in C:
print(row)3 Transpose
matrix = [[1, 2, 3],
[4, 5, 6]]
# 2 rows x 3 cols → 3 rows x 2 cols
rows = len(matrix)
cols = len(matrix[0])
transposed = [[0]*rows for _ in range(cols)]
for i in range(rows):
for j in range(cols):
transposed[j][i] = matrix[i][j]
for row in transposed:
print(row)
# [1, 4]
# [2, 5]
# [3, 6]4 Tic-Tac-Toe Board
board = [[" "]*3 for _ in range(3)]
def print_board(b):
for i, row in enumerate(b):
print(" | ".join(row))
if i < 2:
print("---------")
def place(b, row, col, symbol):
if b[row][col] == " ":
b[row][col] = symbol
return True
return False
place(board, 1, 1, "X")
place(board, 0, 2, "O")
print_board(board)Pitfalls
[[0]*3] * 3 Bug
This creates 3 references to the SAME inner list. Changing one row changes all! Use
[[0]*3 for _ in range(3)] instead.
Row vs Column Confusion
matrix[row][col] — first index is row, second is column. Think [y][x], not [x][y].
Pro-Tips
2D Array Tips
- Rows:
len(matrix). Cols:len(matrix[0]) - Create safely:
[[0]*cols for _ in range(rows)] - Diagonal: elements where
i == j - Common patterns: row sums, column sums, transpose, search
Graded Tasks
How do you access row 2, column 3 of a 2D array?
Why is [[0]*3]*3 dangerous?
Create a 4×4 multiplication table as a 2D array.
Write a function that finds the max element and its position in a 2D array.
Write functions for row sums and column sums of a matrix.
Build a working Tic-Tac-Toe game using a 2D array.