๐ข Exercise Nine: Multidimensional Arrays (Lists)
In Exercise Eight, you learned about one-dimensional listsโa single row of values. But what if you need to represent data that has both rows and columns, like a spreadsheet, a game board, or a matrix in mathematics? This is where multidimensional arrays come in!
- What multidimensional arrays are and why they're useful
- How to create two-dimensional (2D) lists
- How to access and modify elements using row and column indices
- How to use nested loops to process 2D lists
- Common operations on matrices and tables
Think of a 2D array like:
- A spreadsheet โ data organized in rows and columns
- A chessboard โ an 8ร8 grid of squares
- A seating chart โ rows of seats in a theater
- A digital image โ a grid of pixels
- A calendar โ weeks (rows) and days (columns)
๐ 1. What is a Two-Dimensional List?
A two-dimensional (2D) list is essentially a list of lists. Each element of the outer list is itself a list, representing a row of data. This creates a table-like structure with rows and columns.
Creating a 2D List
To create a 2D list, you nest lists inside a list:
# A 2D list representing a 3x4 table (3 rows, 4 columns)
table = [
[1, 2, 3, 4], # Row 0
[5, 6, 7, 8], # Row 1
[9, 10, 11, 12] # Row 2
]
print(table)Visualizing a 2D List
Here's how the table looks conceptually:
table = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
A 2D list is just a list where each element happens to be another list. The outer list contains the rows, and each inner list contains the columns for that row.
๐ฏ 2. Accessing Elements in a 2D List
To access an element in a 2D list, you need two indices: one for the row and one for the column.
list_name[row_index][column_index]Basic Access Examples
table = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
# Access individual elements
print(table[0][0]) # Row 0, Column 0 โ First element
print(table[0][3]) # Row 0, Column 3 โ Last element of first row
print(table[1][2]) # Row 1, Column 2
print(table[2][3]) # Row 2, Column 3 โ Last element4
7
12
Accessing table[1][2] = 7
Accessing an Entire Row
Using a single index gives you an entire row (which is itself a list):
table = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
# Access entire rows
print(table[0]) # Entire first row
print(table[1]) # Entire second row
print(table[2]) # Entire third row[5, 6, 7, 8]
[9, 10, 11, 12]
Getting Dimensions
table = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
num_rows = len(table) # Number of rows
num_cols = len(table[0]) # Number of columns (from first row)
print("Rows:", num_rows)
print("Columns:", num_cols)
print("Total elements:", num_rows * num_cols)Columns: 4
Total elements: 12
Just like with 1D lists, both row and column indices start at 0. A 3ร4 table has row indices 0, 1, 2 and column indices 0, 1, 2, 3.
โ๏ธ 3. Modifying Elements in a 2D List
You can change individual elements using their row and column indices:
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Before:", table)
# Modify individual elements
table[0][0] = 100 # Change top-left corner
table[1][1] = 500 # Change center element
table[2][2] = 900 # Change bottom-right corner
print("After:", table)After: [[100, 2, 3], [4, 500, 6], [7, 8, 900]]
Modifying an Entire Row
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Replace entire row
table[1] = [40, 50, 60]
print(table)๐ 4. Using Nested Loops with 2D Lists
To process every element in a 2D list, you need nested loops: an outer loop for the rows and an inner loop for the columns.
- The outer loop iterates through each row
- The inner loop iterates through each column within that row
- Together, they visit every single element in the 2D list
Method 1: Using Indices with range()
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Process every element using indices
for row in range(len(table)):
for col in range(len(table[row])):
print("table[" + str(row) + "][" + str(col) + "] =", table[row][col])table[0][1] = 2
table[0][2] = 3
table[1][0] = 4
table[1][1] = 5
table[1][2] = 6
table[2][0] = 7
table[2][1] = 8
table[2][2] = 9
How Nested Loops Work
Let's trace through the execution:
| Outer Loop (row) | Inner Loop (col) | Element Accessed | Value |
|---|---|---|---|
| 0 | 0, 1, 2 | table[0][0], table[0][1], table[0][2] | 1, 2, 3 |
| 1 | 0, 1, 2 | table[1][0], table[1][1], table[1][2] | 4, 5, 6 |
| 2 | 0, 1, 2 | table[2][0], table[2][1], table[2][2] | 7, 8, 9 |
Method 2: Direct Iteration Over Rows
You can iterate directly over rows without using indices:
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Iterate directly over rows and elements
for row in table:
for element in row:
print(element, end=" ")
print() # New line after each row4 5 6
7 8 9
- Use indices when you need to know the position (row, column) or modify elements
- Use direct iteration when you just need to read values (simpler syntax)
๐งฎ 5. Common Operations on 2D Lists
Sum of All Elements
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
total = 0
for row in table:
for element in row:
total += element
print("Sum of all elements:", total)Sum of Each Row
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row_index in range(len(table)):
row_sum = 0
for element in table[row_index]:
row_sum += element
print("Sum of row", row_index, ":", row_sum)Sum of row 1 : 15
Sum of row 2 : 24
Sum of Each Column
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
num_cols = len(table[0])
for col in range(num_cols):
col_sum = 0
for row in range(len(table)):
col_sum += table[row][col]
print("Sum of column", col, ":", col_sum)Sum of column 1 : 15
Sum of column 2 : 18
Finding Maximum Value
table = [
[23, 45, 12],
[67, 89, 34],
[56, 11, 78]
]
maximum = table[0][0] # Start with first element
max_row = 0
max_col = 0
for row in range(len(table)):
for col in range(len(table[row])):
if table[row][col] > maximum:
maximum = table[row][col]
max_row = row
max_col = col
print("Maximum value:", maximum)
print("Location: row", max_row, ", column", max_col)Location: row 1 , column 1
Modifying All Elements
# Double every element in the table
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Before:", table)
for row in range(len(table)):
for col in range(len(table[row])):
table[row][col] = table[row][col] * 2
print("After:", table)After: [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
๐๏ธ 6. Creating 2D Lists with Loops
Creating a Table of Zeros
# Create a 3x4 table filled with zeros
rows = 3
cols = 4
table = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
table.append(row)
print(table)Creating a Multiplication Table
# Create a 5x5 multiplication table
size = 5
mult_table = []
for i in range(1, size + 1):
row = []
for j in range(1, size + 1):
row.append(i * j)
mult_table.append(row)
# Print the table nicely
print("Multiplication Table:")
for row in mult_table:
for num in row:
print(str(num).rjust(4), end="")
print()1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Reading a 2D List from User Input
# Get a 2x3 table from user
rows = 2
cols = 3
table = []
print("Enter values for a", rows, "x", cols, "table:")
for i in range(rows):
row = []
for j in range(cols):
value = int(input("Enter value for [" + str(i) + "][" + str(j) + "]: "))
row.append(value)
table.append(row)
print("Your table:", table)Enter value for [0][0]: 1
Enter value for [0][1]: 2
Enter value for [0][2]: 3
Enter value for [1][0]: 4
Enter value for [1][1]: 5
Enter value for [1][2]: 6
Your table: [[1, 2, 3], [4, 5, 6]]
โ 7. Matrix Operations
2D lists are perfect for representing matrices in mathematics. Here are some common matrix operations:
Matrix Addition
To add two matrices, add corresponding elements:
# Add two 2x3 matrices
matrix_a = [
[1, 2, 3],
[4, 5, 6]
]
matrix_b = [
[10, 20, 30],
[40, 50, 60]
]
# Create result matrix
result = []
for i in range(len(matrix_a)):
row = []
for j in range(len(matrix_a[i])):
row.append(matrix_a[i][j] + matrix_b[i][j])
result.append(row)
print("Matrix A:", matrix_a)
print("Matrix B:", matrix_b)
print("A + B =", result)Matrix B: [[10, 20, 30], [40, 50, 60]]
A + B = [[11, 22, 33], [44, 55, 66]]
Transpose a Matrix
Transposing swaps rows and columns:
# Transpose a 2x3 matrix to get a 3x2 matrix
matrix = [
[1, 2, 3],
[4, 5, 6]
]
rows = len(matrix)
cols = len(matrix[0])
# Create transposed matrix (cols x rows)
transposed = []
for j in range(cols):
new_row = []
for i in range(rows):
new_row.append(matrix[i][j])
transposed.append(new_row)
print("Original (2x3):")
for row in matrix:
print(row)
print()
print("Transposed (3x2):")
for row in transposed:
print(row)[1, 2, 3]
[4, 5, 6]
Transposed (3x2):
[1, 4]
[2, 5]
[3, 6]
๐ฏ 8. Complete Examples
Example 1: Grade Book
# Grade book for 4 students, 3 tests each
print("=== Grade Book ===")
print()
students = ["Alice", "Bob", "Charlie", "Diana"]
# Each row is a student, each column is a test
grades = [
[85, 90, 88], # Alice's grades
[78, 82, 80], # Bob's grades
[92, 95, 91], # Charlie's grades
[70, 75, 72] # Diana's grades
]
# Print header
print("Name".ljust(10), "Test1", "Test2", "Test3", "Average")
print("-" * 45)
# Calculate and display each student's average
for i in range(len(students)):
total = 0
for grade in grades[i]:
total += grade
average = total / len(grades[i])
print(students[i].ljust(10), end="")
for grade in grades[i]:
print(str(grade).rjust(6), end="")
print(str(round(average, 1)).rjust(8))
# Calculate class average for each test
print("-" * 45)
print("Class Avg".ljust(10), end="")
for test in range(3):
test_total = 0
for student in range(len(students)):
test_total += grades[student][test]
test_avg = test_total / len(students)
print(str(round(test_avg, 1)).rjust(6), end="")
print()Name Test1 Test2 Test3 Average
---------------------------------------------
Alice 85 90 88 87.7
Bob 78 82 80 80.0
Charlie 92 95 91 92.7
Diana 70 75 72 72.3
---------------------------------------------
Class Avg 81.2 85.5 82.8
Example 2: Tic-Tac-Toe Board
# Tic-Tac-Toe Board Display
print("=== Tic-Tac-Toe ===")
print()
# Board: 'X', 'O', or ' ' for empty
board = [
['X', 'O', 'X'],
[' ', 'X', 'O'],
['O', ' ', 'X']
]
def print_board(b):
"""Display the tic-tac-toe board"""
for i in range(3):
print(" " + b[i][0] + " | " + b[i][1] + " | " + b[i][2])
if i < 2:
print("-----------")
def check_winner(b):
"""Check if there's a winner"""
# Check rows
for row in range(3):
if b[row][0] == b[row][1] == b[row][2] != ' ':
return b[row][0]
# Check columns
for col in range(3):
if b[0][col] == b[1][col] == b[2][col] != ' ':
return b[0][col]
# Check diagonals
if b[0][0] == b[1][1] == b[2][2] != ' ':
return b[1][1]
if b[0][2] == b[1][1] == b[2][0] != ' ':
return b[1][1]
return None # No winner yet
print_board(board)
print()
winner = check_winner(board)
if winner:
print("Winner:", winner)
else:
print("No winner yet")X | O | X
-----------
| X | O
-----------
O | | X
Winner: X
Example 3: Sales Data Analysis
# Monthly sales data for 4 products over 3 months
print("=== Sales Data Analysis ===")
print()
products = ["Widget A", "Widget B", "Gadget X", "Gadget Y"]
months = ["January", "February", "March"]
# Sales data: rows = products, columns = months
sales = [
[150, 200, 175], # Widget A
[300, 280, 320], # Widget B
[120, 150, 180], # Gadget X
[450, 400, 480] # Gadget Y
]
# Find best-selling product overall
best_product = 0
best_total = 0
for i in range(len(products)):
product_total = 0
for j in range(len(months)):
product_total += sales[i][j]
if product_total > best_total:
best_total = product_total
best_product = i
# Find best month overall
best_month = 0
best_month_total = 0
for j in range(len(months)):
month_total = 0
for i in range(len(products)):
month_total += sales[i][j]
if month_total > best_month_total:
best_month_total = month_total
best_month = j
# Calculate grand total
grand_total = 0
for row in sales:
for value in row:
grand_total += value
print("Best-selling product:", products[best_product], "(" + str(best_total) + " units)")
print("Best month:", months[best_month], "(" + str(best_month_total) + " units)")
print("Total sales:", grand_total, "units")Best-selling product: Gadget Y (1330 units)
Best month: March (1155 units)
Total sales: 3205 units
โ ๏ธ Common Mistakes (And How to Fix Them)
Mistake 1: Index Order Confusion
table = [[1, 2, 3], [4, 5, 6]]
# Trying to access row 0, column 1
print(table[1][0]) # This is row 1, column 0 = 4!table = [[1, 2, 3], [4, 5, 6]]
# Access row 0, column 1
print(table[0][1]) # Row first, then column = 2Mistake 2: Index Out of Range
table = [[1, 2, 3], [4, 5, 6]] # 2 rows, 3 columns
print(table[2][0]) # ERROR! Row index 2 doesn't existtable = [[1, 2, 3], [4, 5, 6]] # 2 rows, 3 columns
print(table[1][0]) # Max row index is 1 (len-1)Mistake 3: Wrong Loop Limits
table = [[1, 2, 3], [4, 5, 6]]
for i in range(3): # Wrong! Only 2 rows
for j in range(2): # Wrong! 3 columns
print(table[i][j])table = [[1, 2, 3], [4, 5, 6]]
for i in range(len(table)): # Number of rows
for j in range(len(table[i])): # Number of columns
print(table[i][j])Mistake 4: Creating 2D List Incorrectly
row = [0, 0, 0]
table = [row, row, row] # All three rows are the SAME list!
table[0][0] = 5
print(table) # [[5, 0, 0], [5, 0, 0], [5, 0, 0]] - Oops!table = []
for i in range(3):
table.append([0, 0, 0]) # New list for each row
table[0][0] = 5
print(table) # [[5, 0, 0], [0, 0, 0], [0, 0, 0]] - Correct!Mistake 5: Modifying While Iterating Directly
table = [[1, 2], [3, 4]]
for row in table:
for elem in row:
elem = elem * 2 # This doesn't change the table!table = [[1, 2], [3, 4]]
for i in range(len(table)):
for j in range(len(table[i])):
table[i][j] = table[i][j] * 2โ๏ธ Practice Exercises
Try writing these programs on your own!
Exercise 1: Matrix Sum and Average
Write a program that:
- Creates a 3ร4 matrix of numbers
- Calculates and displays the sum of all elements
- Calculates and displays the average of all elements
Exercise 2: Row and Column Sums
Write a program that:
- Creates a 4ร4 matrix of numbers
- Prints the sum of each row
- Prints the sum of each column
- Identifies which row has the largest sum
Exercise 3: Diagonal Sum
Write a program that:
- Creates a square matrix (e.g., 4ร4)
- Calculates the sum of the main diagonal (top-left to bottom-right)
- Calculates the sum of the anti-diagonal (top-right to bottom-left)
Hint: For main diagonal, row index equals column index!
Exercise 4: Find and Replace
Write a program that:
- Creates a 2D list of numbers
- Asks the user for a value to find
- Asks the user for a replacement value
- Replaces all occurrences and shows the result
Exercise 5: Matrix Border
Write a program that creates a matrix and sets all border elements to 1 and interior elements to 0:
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
Hint: An element is on the border if row is 0 or last, or column is 0 or last.
Exercise 6: Seating Chart
Write a program that simulates a movie theater seating chart:
- Create a 5ร8 grid (5 rows, 8 seats per row)
- Use 'O' for available and 'X' for taken
- Display the seating chart
- Let the user reserve a seat by entering row and column
- Count and display the number of available seats
๐ Quick Reference
Creating 2D Lists
table = [
[1, 2, 3],
[4, 5, 6]
]table = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
table.append(row)Accessing Elements
table[row][col]table[row]len(table)len(table[0])Nested Loop Patterns
for i in range(len(table)):
for j in range(len(table[i])):
print(table[i][j])for row in table:
for elem in row:
print(elem)โญ Key Takeaways
- โ A 2D list is a list of lists (each element is a row)
- โ Access elements with two indices:
table[row][col] - โ Indices start at 0 for both rows and columns
- โ Use
len(table)for number of rows - โ Use
len(table[0])for number of columns - โ Nested loops are essential for processing 2D lists
- โ Outer loop iterates over rows, inner loop iterates over columns
- โ Use indices when you need to modify elements or know positions
- โ Use direct iteration when you just need to read values
- โ When creating 2D lists with loops, create a new list for each row
โ Need Help?
If your program doesn't work, check these common issues:
- IndexError: list index out of rangeโCheck your row and column indices. Remember they start at 0!
- Wrong element accessedโRemember: row first, then column:
table[row][col] - Loop not processing all elementsโUse
len()instead of hardcoded numbers - Changes not appearingโUse indices to modify; direct iteration doesn't change original
- Rows sharing changesโMake sure each row is a separate list object
for i in range(len(table)):
for j in range(len(table[i])):
print("table[" + str(i) + "][" + str(j) + "] =", table[i][j])