Iterating Through 2D Arrays
What you'll learn: How to visit every element in a 2D array using nested loops in different traversal patterns.
The Core Idea
A 2D array is like a grid or spreadsheet—it has rows and columns. To visit every cell, you need two loops: an outer loop to move through rows, and an inner loop to move through columns within each row. This is called a nested loop pattern.
Think of reading a book: the outer loop picks each page (row), and the inner loop reads each line (column) on that page.
Row-by-Row Traversal
The most common pattern visits all elements row-by-row, left to right:
# Assume grid is a 2D array with 3 rows and 4 columns
for row in range(3): # Outer loop: each row
for col in range(4): # Inner loop: each column in that row
element = grid[row][col]
# Process element
The outer loop controls which row you're in, and the inner loop moves across that entire row before moving to the next one.
Column-by-Column Traversal
Sometimes you need to process columns first (like reading vertically):
for col in range(4): # Outer loop: each column
for row in range(3): # Inner loop: each row in that column
element = grid[row][col]
# Process element
Notice how we simply swapped which index changes in the outer vs inner loop!
Key Pattern
For any 2D array, the traversal structure is:
- Outer loop controls one dimension
- Inner loop controls the other dimension
- Access elements with
array[outerIndex][innerIndex]
Key Takeaway: Use nested loops to iterate through 2D arrays—the outer loop picks rows (or columns), and the inner loop moves through columns (or rows) within each iteration of the outer loop.