How to Build a Coordinate Grid with Nested Loops in Python

Generate a 2D list of (row, col) coordinate pairs using nested loops and return the grid structure.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

15 lines
Python 3.9+
def build_coordinate_grid(rows, cols):
    """Build a 2D grid of (row, col) coordinates using nested loops."""
    grid = []
    for r in range(rows):
        row = []
        for c in range(cols):
            row.append((r, c))
        grid.append(row)
    return grid


if __name__ == "__main__":
    grid = build_coordinate_grid(3, 4)
    for row in grid:
        print(row)

Output

stdout
[(0, 0), (0, 1), (0, 2), (0, 3)]
[(1, 0), (1, 1), (1, 2), (1, 3)]
[(2, 0), (2, 1), (2, 2), (2, 3)]

How it works

The outer loop runs once per row, creating a new list row for each row. The inner loop runs once for each column, appending the tuple (r, c) to the current row. After the inner loop finishes, the completed row is appended to the main grid list, building the 2D structure. The double loop gives us O(rows × cols) complexity, unavoidable since we must touch every cell.

Common mistakes

  • Forgetting to reinitialize `row` inside the outer loop, causing all rows to accumulate coordinates.
  • Using `grid.append((r, c))` directly, which produces a flat list instead of a 2D grid.
  • Swapping `rows` and `cols` in the loop order, resulting in a transposed grid.

Variations

  1. Use a list comprehension: `grid = [[(r, c) for c in range(cols)] for r in range(rows)]`
  2. Use `itertools.product` then chunk into rows for a more compact but less explicit approach.

Real-world use cases

  • Setting up a board game like Chess or Battleship where you need a matrix of cell positions.
  • Representing pixel coordinates for image processing and iterating over an image matrix.
  • Creating 2D data structures for map tiles in a grid-based game or GIS application.

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.