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.
Python code
30 linesdef 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
[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
- Use numpy for vectorized neighbor counting via shifted array slices or convolution
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.