Nested Lists: Processing & Algorithms
Once a 2D matrix is initialized, programs must perform algorithmic operations: calculating row and column totals, navigating main and secondary diagonals, locating maximum elements with their indices, and transposing tables.
Learning Objectives
- 11.2.3.4 Create and manipulate nested lists in Python
- 11.2.3.6 Define the difference between different data structures
- 11.3.3.4 Solve applied problems from various subject areas
Lesson Presentation
11.3A-lesson-18-nested-lists-processing.pdf · Slides for classroom use
Conceptual Anchor
The Meteorological Heatmap
Weather stations record temperatures across a regional geographic grid ($N \times M$). To extract insights, meteorologists calculate the average daily temperature per row (latitude bands), column maximums (peak regional stations), and cross-diagonal thermal fronts.
Rules & Theory
1. Traversal by Element vs Traversal by Index
matrix = [[1, 2, 3], [4, 5, 6]]
# Traversal by element (read-only)
for row in matrix:
for val in row:
print(val, end=" ")
# Traversal by indices (needed when modifying or needing coordinates)
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
print(f"cell({i},{j}) = {matrix[i][j]}")2. Row Sums vs Column Sums
| Calculation | Code Example | Logic |
|---|---|---|
| Row Sums | row_sums = [sum(row) for row in matrix] |
Trivial: Python's sum() works directly on each inner list. |
| Column Sums | col_sums = [sum(matrix[i][j] for i in range(rows)) for j in range(cols)] |
Outer loop runs across columns j, inner loop sums down rows i. |
3. Diagonal Rules for $N \times N$ Square Matrices
| Region | Condition on Indices $(i, j)$ | Description |
|---|---|---|
| Main Diagonal | i == j |
Top-left to bottom-right: (0,0), (1,1), (2,2) |
| Secondary Diagonal | i + j == n - 1 (or matrix[i][n - 1 - i]) |
Top-right to bottom-left |
| Above Main Diagonal | j > i |
Upper triangular matrix |
| Below Main Diagonal | j < i |
Lower triangular matrix |
Worked Examples
1 Locating the Global Maximum and its Coordinates
Find the highest value in an $N \times M$ matrix along with its row and column index:
matrix = [
[12, 45, 19],
[87, 23, 91],
[54, 68, 33]
]
max_val = matrix[0][0]
max_row, max_col = 0, 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] > max_val:
max_val = matrix[i][j]
max_row, max_col = i, j
print(f"Maximum value: {max_val} at Row {max_row}, Column {max_col}")
# Output: Maximum value: 91 at Row 1, Column 22 Calculating Main and Secondary Diagonal Sums
Summing both diagonals in a single loop with $O(N)$ time complexity:
n = 3
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
main_sum = 0
sec_sum = 0
for i in range(n):
main_sum += grid[i][i] # 1 + 5 + 9 = 15
sec_sum += grid[i][n - 1 - i] # 3 + 5 + 7 = 15
print(f"Main diagonal sum: {main_sum}")
print(f"Secondary diagonal sum: {sec_sum}")3 Matrix Transposition (Flipping Rows and Columns)
Convert an $M \times N$ matrix into an $N \times M$ transposed matrix:
table = [
["Alice", 95, "A"],
["Bob", 82, "B"],
["Clara", 89, "A"]
]
# Method A: Comprehension
transposed = [[row[j] for row in table] for j in range(len(table[0]))]
# Method B: zip() unpacker
transposed_fast = [list(col) for col in zip(*table)]
for line in transposed_fast:
print(line)
# ['Alice', 'Bob', 'Clara']
# [95, 82, 89]
# ['A', 'B', 'A']Pitfalls & Common Errors
Non-Square Matrices and Diagonal Assumptions
Diagonals only make mathematical sense for square ($N \times N$) matrices. If a matrix is rectangular ($3 \times 5$), accessing matrix[i][n - 1 - i] where $n = 3$ will ignore the remaining columns!
O(N²) when O(N) is Possible
To access diagonal elements, beginners often write nested loops with if i == j:, which takes $N^2$ iterations. A single loop for i in range(n): total += matrix[i][i] does it in $N$ operations.
Pro-Tips for Exams
Exam Checklist
- Flattening a 2D list into a 1D list:
flat = [num for row in matrix for num in row]. - Global minimum:
min(min(row) for row in matrix). - Symmetric matrix check:
all(matrix[i][j] == matrix[j][i] for i in range(n) for j in range(n)).
Graded Tasks
State the relationship between row index $i$ and column index $j$ for cells on the secondary diagonal of an $N \times N$ matrix.
Explain how zip(*matrix) works to transpose a matrix in Python.
Write a program that takes an $N \times M$ matrix of integers and replaces all negative numbers with zeros.
Write an algorithm to determine whether a given square matrix is symmetric with respect to its main diagonal.
Build a "Magic Square Checker": verify whether an $N \times N$ grid has equal sums for all rows, all columns, and both diagonals.
Self-Check Quiz
m?len(matrix[0]) represent in a rectangular matrix?