Multi-dimensional lists
Multi-dimensional collection of data
Multi-dimensional Lists
In the previous lesson we worked with 1D lists — a single row of values. Now let's go one step further: a multi-dimensional list is a list where each element is itself a list. This gives us a table of rows and columns, which in programming is called a matrix.
Creating a 2D List
This is a 3×3 matrix. matrix is a list of 3 rows, and each row is a list of 3 integers.
Accessing Elements
To access an element you need two indices: matrix[row][col]. Both start at 0:
You can also modify any element the same way:
Dimensions
len(matrix) gives the number of rows. len(matrix[0]) gives the number of columns:
Iterating Over a 2D List
Use nested loops — the outer loop over rows, the inner loop over columns:
Output:
If you only need values and don't care about indices, you can iterate directly:
Or print each row in one shot using *:
Creating a 2D List with Loops
For a fixed small matrix you can write it out manually. But for larger or dynamic sizes, build it with a loop.
The correct way — list comprehension
The wrong way — do NOT do this
This looks correct but creates rows references to the same inner list. Modifying one row modifies all of them:
Always use the list comprehension form to create 2D lists.
Reading a Matrix from Input
The standard CP format: first line is n and m, then n lines each with m integers:
Or more compactly:
Practical Examples
Filling with sequential numbers
Output:
Finding the maximum element and its position
Sum of each row
Transposing a matrix
The transpose of a matrix swaps rows and columns — matrix[i][j] becomes transposed[j][i]:
Diagonal elements
For a square n×n matrix, the main diagonal is where i == j:
The secondary diagonal is where i + j == n - 1:
Beyond 2D
The same idea extends to 3D and higher — a list of matrices is a 3D structure: