2D Arrays (Nested Lists)
Learn how to work with data organised in rows and columns, like a table or grid.
What you'll learn:
- What 2D arrays are and when to use them
- Creating 2D arrays (lists of lists)
- Accessing elements using two indices: [row][column]
- Using nested loops to iterate through 2D arrays
- Practical applications: grids, tables, matrices
Learning Path
Follow these activities in order.
1. Predict: What's in the Grid?
Predict what 2D array operations will output.
2. Study: Worked Example
See how to create and navigate 2D arrays step by step.
3. Investigate: Trace Nested Loops
Track how nested loops iterate through a 2D array.
4. Modify: Arrange the Code
Put code blocks in order to work with 2D arrays.
5. Test: Knowledge Quiz
Check your understanding of 2D arrays.
Key Vocabulary
2D array
An array of arrays - data organised in rows and columns, like a table or spreadsheet.
row
A horizontal line in a 2D array. The first index selects which row.
column
A vertical line in a 2D array. The second index selects which column.
nested loop
A loop inside another loop. Used to visit every element in a 2D array.
grid
Another name for a 2D array. Think of game boards, maps, or spreadsheets.
matrix
A mathematical term for a 2D array of numbers. Used in maths and graphics.
Quick Reference
# Creating a 2D array (3 rows x 4 columns)
grid = [
[1, 2, 3, 4], # Row 0
[5, 6, 7, 8], # Row 1
[9, 10, 11, 12] # Row 2
]
# Accessing elements: array[row][column]
print(grid[0][0]) # First row, first column: 1
print(grid[1][2]) # Second row, third column: 7
print(grid[2][3]) # Third row, fourth column: 12
# Getting a whole row
print(grid[1]) # [5, 6, 7, 8]
# Number of rows and columns
rows = len(grid) # 3 rows
cols = len(grid[0]) # 4 columns
# Nested loop - print every element
for row in grid:
for item in row:
print(item, end=" ")
print() # New line after each row
# Nested loop with indices
for r in range(len(grid)):
for c in range(len(grid[r])):
print(grid[r][c], end=" ")
Visualising a 2D Array
Think of a 2D array as a table with rows and columns:
| Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
| Row 0 | grid[0][0]"A" |
grid[0][1]"B" |
grid[0][2]"C" |
| Row 1 | grid[1][0]"D" |
grid[1][1]"E" |
grid[1][2]"F" |