Creating a 2D List

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

# Or dynamically (3×4 of zeros):
rows, cols = 3, 4
grid = [[0] * cols for _ in range(rows)]
⚠️ Do NOT write [[0]*cols]*rows — all rows become the same list.

Accessing Cells

print(grid[0][2])   # row 0, col 2
grid[1][1] = 99

Transposing

transposed = [list(row) for row in zip(*grid)]

Row and Column Sums

row_totals = [sum(row) for row in grid]
col_totals = [sum(col) for col in zip(*grid)]

Diagonals

n = len(grid)
diag = [grid[i][i] for i in range(n)]
anti = [grid[i][n-1-i] for i in range(n)]

Flood Fill (Mini Example)

def flood(g, r, c, target, replacement):
    if g[r][c] != target: return
    g[r][c] = replacement
    for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
        nr, nc = r+dr, c+dc
        if 0 <= nr < len(g) and 0 <= nc < len(g[0]):
            flood(g, nr, nc, target, replacement)

Practise this on PyForm — free

PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.

Open PyForm →