How to Create Matrix in Python?

Use a nested list

`matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]`

Create an empty matrix with loops

`matrix = []`

`for i in range(3):`

` row = []`

` for j in range(3):`

` row.append(0)`

` matrix.append(row)`

Use list comprehension

`matrix = [[0 for _ in range(3)] for _ in range(3)]`

Use NumPy

`import numpy as np`

`matrix = np.array([[1, 2], [3, 4]])`

Create an identity matrix with NumPy

`identity = np.eye(3)`

Create a matrix of zeros with NumPy

`zeros = np.zeros((3, 3))`

Create a matrix of ones with NumPy

`ones = np.ones((3, 3))`

Suggested for You

Trending Today