Lesson 5 of 18
Matrices
Matrices in Python
A matrix is a 2D array of numbers with rows and columns — an matrix. In Python, we represent it as a list of lists.
A = [[1, 2, 3],
[4, 5, 6]]
print(A) # [[1, 2, 3], [4, 5, 6]]
print(len(A)) # 2 — rows
print(len(A[0])) # 3 — columns
print(A[0][1]) # 2 — row 0, column 1
print(A[1]) # [4, 5, 6] — entire row 1
Special Matrices
# Zeros matrix (3×4)
zeros = [[0]*4 for _ in range(3)]
# Identity matrix (3×3)
I = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
# [[1, 0, 0],
# [0, 1, 0],
# [0, 0, 1]]
The Identity Matrix
The identity matrix is the matrix equivalent of the number 1: for any matrix . It has 1s on the diagonal and 0s everywhere else.
Your Task
Implement identity(n) that returns the identity matrix as a list of lists.
Pyodide loading...
Loading...
Click "Run" to execute your code.