Open In App

Initialize Matrix in Python

Last Updated : 29 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Initializing a matrix in Python refers to creating a 2D structure (list of lists) to store data in rows and columns. For example, a 3x2 matrix can be represented as three rows, each containing two elements. Let’s explore different methods to do this efficientely.

Using list comprehension

List comprehension creates the matrix by building each element separately in nested loops, ensuring each row is independent. Very flexible for initializing with any values or expressions. Slightly longer but avoids shared references.

Python
rows = 3
cols = 2

res = [[0 for _ in range(cols)] for _ in range(rows)]
print(res)

Output
[[0, 0], [0, 0], [0, 0]]

Explanation: (for _ in range(rows)) runs three times to create three rows. For each row, the inner loop ([0 for _ in range(cols)]) runs twice to generate a list with two zeros.

Using Multiplication inside list comprehension

Builds each row by repeating zeros and replicates rows with a list comprehension, producing independent rows. It’s shorter and faster for simple zero matrices. Best for uniform initialization.

Python
rows = 3
cols = 2

res = [[0]*cols for _ in range(rows)]
print(res)

Output
[[0, 0], [0, 0], [0, 0]]

Explanation: (for _ in range(rows)) runs three times to create three rows. For each row, [0]*cols creates a new list with two zeros by multiplying the value 0 by the number of columns.

Using numpy zeros

Generates a fast, memory-efficient 2D array of zeros using NumPy, ideal for numeric data and large matrices. Returns a NumPy array instead of a list. Great for scientific or vectorized operations.

Python
import numpy as np

rows, cols = 3, 2
res = np.zeros((rows, cols), dtype=int)
print(res)

Output
[[0 0]
 [0 0]
 [0 0]]

Explanation: np.zeros((rows, cols), dtype=int) function generates a matrix where each element is initialized to 0 and dtype=int ensures the values are integers.

Using * with deep copy

Creates one zero-filled row and deep copies it multiple times to prevent shared references between rows. Useful when matrix elements are mutable objects. Slightly slower due to deep copying overhead.

Python
import copy
rows, cols = 3, 2

row = [0] * cols
res = [copy.deepcopy(row) for _ in range(rows)]
print(res)

Output
[[0, 0], [0, 0], [0, 0]]

Explanation: This code first creates a single row with two zeros using [0] * cols. It then uses copy.deepcopy(row) in a list comprehension to create three separate copies of that row.


Next Article

Similar Reads