How to create an empty matrix in Python [3 ways]

In this NumPy tutorial, I will explain how to create an empty matrix in Python using different methods with some illustrative examples.

To create an empty matrix in Python, we can use a list comprehension or leverage NumPy’s zeros and empty functions. For a simple empty matrix with lists, use matrix = [[None]*columns for _ in range(rows)]. With NumPy, numpy.zeros((rows, columns)) creates a matrix filled with zeros, while numpy.empty((rows, columns)) initializes an empty matrix without setting values, which is faster but contains arbitrary data.

Create an empty matrix in Python

There are two different ways to create an empty matrix in Python:

  • Using lists
  • Using NumPy functions

Let’s see them one by one with examples:

1. How to create empty matrix in Python using lists

In Python, an empty matrix can be created as a list of lists. The size of the matrix can be defined, but initially, it won’t contain any data.

empty_matrix = [[None]*3 for _ in range(3)]
print(empty_matrix)

Output: In this example, None is used as a placeholder. The size of the matrix is 3×3, but it can be adjusted as needed.

[[None, None, None], [None, None, None], [None, None, None]]
create an empty matrix in Python

2. Create an empty matrix in Python using NumPy functions

NumPy offers more efficient ways to create empty matrices. It’s important to note that an empty matrix in NumPy may contain arbitrary data and should be explicitly set before use.

2.1. np.empty() finction to create an empty matrix in Python

The np.empty function creates a matrix without initializing its values, which is faster than initializing values.

import numpy as np

empty_matrix = np.empty((0, 0))
print(empty_matrix)

Output: Here an empty array will be created.

[]
empty matrix in python

2.2. Create empty matrix Python using np.zeros() function

Alternatively, we can create a matrix initialized with zeros, which is another form of an empty matrix in Python.

import numpy as np

zero_matrix = np.zeros((3, 3))
print(zero_matrix)

Output: Here a 2D array will be created with 0.

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
empty matrix python

Conclusion

Here, we have learned how to create an empty matrix in Python, using list comprehension, numpy.zeros() function, and numpy.empty() function with some illustrative examples.

The choice of the method depends on the requirements of the problem one is dealing with.

You may also like the following Python tutorials: