Nested Lists
2D lists and matrices
Interview Relevant: Matrix problems
Nested Lists
Lists within lists for 2D data.
Code Examples
Working with 2D lists and matrices.
python
1# 2D list (matrix)
2matrix = [
3 [1, 2, 3],
4 [4, 5, 6],
5 [7, 8, 9]
6]
7
8# Access elements
9matrix[0][0] # 1
10matrix[1][2] # 6
11
12# Iterate rows
13for row in matrix:
14 print(row)
15
16# Iterate all elements
17for i in range(len(matrix)):
18 for j in range(len(matrix[0])):
19 print(matrix[i][j])
20
21# Create 3x3 matrix of zeros
22# WRONG way (shared reference!)
23wrong = [[0] * 3] * 3
24
25# RIGHT way
26correct = [[0 for _ in range(3)] for _ in range(3)]
27
28# Transpose matrix
29transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
30# Or: list(zip(*matrix))