Introduction to Python Programming

Andrew J. Pounds, Ph.D.

๐Ÿ”ข 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 You'll Learn:
  • 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
๐ŸŒ Real-World Analogies:

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)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Visualizing a 2D List

Here's how the table looks conceptually:

table = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Row 0
Row 1
Row 2
1
2
3
4
5
6
7
8
9
10
11
12
Col 0
Col 1
Col 2
Col 3
๐Ÿ’ก Key Insight:

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 element
1
4
7
12

Accessing table[1][2] = 7

Row 0
Row 1 โ†
Row 2
1
2
3
4
5
6
7
8
9
10
11
12
Col 0
Col 1
Col 2 โ†‘
Col 3

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
[1, 2, 3, 4]
[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)
Rows: 3
Columns: 4
Total elements: 12
โš ๏ธ Remember Zero-Based Indexing!

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)
Before: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
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)
[[1, 2, 3], [40, 50, 60], [7, 8, 9]]

๐Ÿ”„ 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.

โœ… Why Nested Loops are Essential:
  • 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][0] = 1
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 row
1 2 3
4 5 6
7 8 9
๐Ÿ’ก Which Method to Use?
  • 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 all elements: 45

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 0 : 6
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 0 : 12
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)
Maximum value: 89
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)
Before: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
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)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

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()
Multiplication Table:
   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 values for a 2 x 3 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 A: [[1, 2, 3], [4, 5, 6]]
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)
Original (2x3):
[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()
=== Grade Book ===

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")
=== Tic-Tac-Toe ===

 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")
=== Sales Data Analysis ===

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

โŒ Wrong (confusing row and column):
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!
โœ… Correct:
table = [[1, 2, 3], [4, 5, 6]]
# Access row 0, column 1
print(table[0][1])  # Row first, then column = 2

Mistake 2: Index Out of Range

โŒ Wrong:
table = [[1, 2, 3], [4, 5, 6]]  # 2 rows, 3 columns
print(table[2][0])  # ERROR! Row index 2 doesn't exist
โœ… Correct:
table = [[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

โŒ Wrong (hardcoding dimensions):
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])
โœ… Correct (using len()):
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

โŒ Wrong (all rows reference same list!):
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!
โœ… Correct (create new list for each row):
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

โŒ Wrong (doesn't modify the original):
table = [[1, 2], [3, 4]]
for row in table:
    for elem in row:
        elem = elem * 2  # This doesn't change the table!
โœ… Correct (use indices to modify):
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:

  1. Creates a 3ร—4 matrix of numbers
  2. Calculates and displays the sum of all elements
  3. Calculates and displays the average of all elements

Exercise 2: Row and Column Sums

Write a program that:

  1. Creates a 4ร—4 matrix of numbers
  2. Prints the sum of each row
  3. Prints the sum of each column
  4. Identifies which row has the largest sum

Exercise 3: Diagonal Sum

Write a program that:

  1. Creates a square matrix (e.g., 4ร—4)
  2. Calculates the sum of the main diagonal (top-left to bottom-right)
  3. 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:

  1. Creates a 2D list of numbers
  2. Asks the user for a value to find
  3. Asks the user for a replacement value
  4. 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 1 1 1 1
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:

  1. Create a 5ร—8 grid (5 rows, 8 seats per row)
  2. Use 'O' for available and 'X' for taken
  3. Display the seating chart
  4. Let the user reserve a seat by entering row and column
  5. Count and display the number of available seats

๐Ÿ“‹ Quick Reference

Creating 2D Lists

Direct creation:
table = [
    [1, 2, 3],
    [4, 5, 6]
]
Using loops:
table = []
for i in range(rows):
    row = []
    for j in range(cols):
        row.append(0)
    table.append(row)

Accessing Elements

Single element:
table[row][col]
Entire row:
table[row]
Number of rows:
len(table)
Number of columns:
len(table[0])

Nested Loop Patterns

With indices:
for i in range(len(table)):
    for j in range(len(table[i])):
        print(table[i][j])
Direct iteration:
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:

  1. IndexError: list index out of rangeโ€”Check your row and column indices. Remember they start at 0!
  2. Wrong element accessedโ€”Remember: row first, then column: table[row][col]
  3. Loop not processing all elementsโ€”Use len() instead of hardcoded numbers
  4. Changes not appearingโ€”Use indices to modify; direct iteration doesn't change original
  5. Rows sharing changesโ€”Make sure each row is a separate list object
๐Ÿ’ก Debugging Tip: Print the indices and values to see what's happening:
for i in range(len(table)):
    for j in range(len(table[i])):
        print("table[" + str(i) + "][" + str(j) + "] =", table[i][j])
Remember: 2D lists open up a whole new world of programming possibilities! From game boards to spreadsheets to image processing, understanding how to work with rows and columns of data is a fundamental skill. Practice creating, accessing, and modifying 2D lists until the row-column indexing becomes second nature. Combined with nested loops, you'll be able to process any tabular data efficiently!