Game of Life Next State Grid in Python

Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

30 lines
Python 3.9+
def next_state(grid):
    m, n = len(grid), len(grid[0])
    new = [[0] * n for _ in range(m)]
    for r in range(m):
        for c in range(n):
            total = 0
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    if dr == 0 and dc == 0:
                        continue
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < m and 0 <= nc < n:
                        total += grid[nr][nc]
            if grid[r][c] == 1:
                new[r][c] = 1 if total in (2, 3) else 0
            else:
                new[r][c] = 1 if total == 3 else 0
    return new


if __name__ == "__main__":
    grid = [
        [0, 1, 0],
        [0, 0, 1],
        [1, 1, 1],
        [0, 0, 0],
    ]
    result = next_state(grid)
    for row in result:
        print(row)

Output

stdout
[0, 0, 0]
[1, 0, 1]
[0, 1, 1]
[0, 1, 0]

How it works

The code iterates over every cell and counts its eight live neighbors using nested (-1,0,1) loops. A live cell survives only with 2 or 3 neighbors, while a dead cell becomes alive exactly with 3 neighbors — the classic Conway rules. The new grid is built from scratch each generation, so updates are independent and don't affect neighbor counts. Edge cells skip out-of-bound coordinates gracefully, keeping the logic clean without padding.

Common mistakes

  • Mutating the original grid in place, which corrupts neighbor counts for later cells
  • Forgetting to skip the cell itself when counting its eight neighbors
  • Misapplying rules, e.g., letting a live cell with 3 neighbors die or a dead cell with 2 neighbors live

Variations

  1. Use numpy for vectorized neighbor counting via shifted array slices or convolution
  2. Implement with a padded border of zeros to simplify edge handling without bounds checks

Real-world use cases

  • Simulating population dynamics or spread of phenomena on a cellular automaton grid for research or teaching.
  • Building animated visualizations or interactive demos of Conway's Game of Life in web or desktop apps.
  • Prototyping grid-based AI or procedural generation patterns where local neighbor interactions drive state changes.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.