Python 2D Lists and Grids for Board Games
How to make and use 2D lists (grids) in Python for board games: create rows safely, read grid[row][col], check neighbours, and print a board.
Board games need a grid: rows and columns. In Python a grid is a list of lists: a list of rows, where each row is a list of cells. grid[row][col] reads one cell.
Checking neighbours
Minesweeper-style games look at the 8 cells around a square. Loop over -1, 0 and 1 in both directions, skip the cell itself, and stay inside the edges.
Rows, columns and boxes
- A row is
grid[r]. - A column is
[grid[i][c] for i in range(ROWS)]. - A 3×3 box (Sudoku) starts at
r // 3 * 3,c // 3 * 3. - Copy a grid with
[row[:] for row in grid], notgrid[:].
💡 [["."] * 4] * 3 looks right but every row is the same list, so changing one cell changes a whole column.
Games that use 2D lists and grids
Practise this with 5 of the 20 games:
- #09☆☆☆
Connect Four-Style Game in Python
Learn 2D lists and grids, Lists and Functions.
- #10☆☆☆
Minesweeper-Style Game in Python
Learn 2D lists and grids, Functions and for loops.
- #11☆☆☆
Sudoku in Python
Learn 2D lists and grids, Functions and for loops.
- #12☆☆☆
Battleship-Style Game in Python
Learn 2D lists and grids, The random module and Strings.
- #13☆☆☆
Maze Game in Python
Learn 2D lists and grids, Functions and Lists.
Frequently asked questions
How do you make a 2D list in Python?
Use a list comprehension: [[0 for _ in range(cols)] for _ in range(rows)]. Each row is then its own list.
Is it grid[x][y] or grid[y][x]?
With a list of rows it's grid[row][col], which means grid[y][x]. Mixing them up is the most common grid bug.