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.
Python code
15 linesdef 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
[(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
- Use a list comprehension: `grid = [[(r, c) for c in range(cols)] for r in range(rows)]`
- 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
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.