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]]
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.
[]
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.]]
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:
- Python NumPy Matrix Operations
- Python NumPy Matrix Multiplication
- How to Create a 2D NumPy Array in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.