Lesson 12: Multidimensional Lists
Multidimensional lists are basically lists inside a list—also known as lists of lists. We can imagine multidimensional lists as a table in memory, sometimes called a matrix.
Let's look at an example:
matrix = [[5, 7, 6, 2], [0, 5, 8, 5], [7, 9, 4, 1], [6, 3, 4, 2]]
| y \ x | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 5 | 7 | 6 | 2 |
| 1 | 0 | 5 | 8 | 5 |
| 2 | 7 | 9 | 4 | 1 |
| 3 | 6 | 3 | 4 | 2 |
matrix[3]→[6, 3, 4, 2]matrix[0]→[5, 7, 6, 2]matrix[2][3]→1(Row 2, Column 3)matrix[1][0]→0(Row 1, Column 0)
Basically, the first argument in square brackets is the index of the row/list you want to access, and the second argument is the specific element inside that inner list.
Note that lists inside a list don’t have to be the same length:
jagged = [[8, 22, 4, 3, 1], [5, 6], [4, 3, 87, 4], [], [5]]
jagged[3] # → []
jagged[0][2] # → 4
jagged[1][2] # → ERROR! (Index out of range)
Multidimensional List Exercises:
1st Exercise:
You are given a 2D matrix (a list of lists) with numbers. Click to copy:
Your Tasks:
- Loop through the matrix using nested loops and calculate the total sum of all numbers in it.
- Find the maximum number in the matrix and print it.
Reveal Answer
matrix = [[3, 8, 1],[5, 2, 9],[7, 4, 6]]
sum = 0
maxNumber = matrix[0][0]
for row in matrix:
for num in row:
sum += num
if num > maxNumber:
maxNumber = num
print(f"The total sum is {sum}")
print(f"The biggest number is {maxNumber}")Output
The total sum is 45
The biggest number is 92nd Exercise:
You are given a 2D matrix with numbers. Click to copy:
Your Task: Write a program that calculates the sum of numbers for each row separately and stores these sums in a new list. For the given matrix, your final list of row sums should look like this: [6, 15, 24]
Reveal Answer
matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
sums = []
for row in matrix:
a=0
for num in row:
a+=num
sums.append(a)
print(sums)Output
[6, 15, 24]Want XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 12