Multi-dimensional lists
Introduction to 2D lists and matrices — creation, access, iteration, input reading, and practical examples including transposition and diagonal traversal.
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
Note: The
for _ in range(rows)part inside the brackets is a list comprehension — a compact way to build lists that will be covered in detail in a later module. For now, treat this as the standard recipe for creating a 2D list of a given size.
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 using a list comprehension:
Note: The compact version uses list comprehensions, which will be covered in detail in a later module. Both versions produce the same result.
Practical Examples
Filling with sequential numbers
Output:
Finding the maximum element and its position
Input: |