With all below code snippets you can create a 3 * 3 matrix with python:
First method: Appending columns inside of loops for each row
rows = 3
cols = 3
lst = []
matrix = []
for i in range(rows):
for j in range(cols):
lst.append(0)
matrix.append(lst)
lst.clear()
print(matrix)
# the output will be: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrix[1][1] = 1
print(matrix)
# the output will be: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Second method: 1 list comprehension outside and 1 concatenation operation inside
rows = 3
cols = 3
matrix = [[0] * cols for _ in range(rows)]
print(matrix)
# the output will be: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrix[1][1] = 1
print(matrix)
# the output will be: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Third method: 1 list comprehension inside and 1 concatenation operation outside
rows = 3
cols = 3
matrix = [[0 for _ in range(cols)]] * rows
print(matrix)
# the output will be: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrix[1][1] = 1
print(matrix)
# the output will be: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Fourth method: Using numpy
package
import numpy as np
rows = 3
cols = 3
size = rows*cols
matrix = np.array([0]*size).reshape(rows,cols)
print(matrix)
# the output will be: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrix[1][1] = 1
print(matrix)
# the output will be: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]