Home »
Python »
Python Programs
NumPy Matrix of All True or All False
In this tutorial, we will learn how to create a NumPy matrix of all True or all False?
By Pranit Sharma Last updated : May 25, 2023
Suppose we need to create a numpy matrix of length n x n, and each element of this array would be either True or False.
How to create a NumPy Matrix of All True or All False?
There are three different approaches that you can use to create a NumPy matrix of all True or all False,
- Using numpy.full() Method
- Using numpy.ones() Method
- Using numpy.zeroes() Method
1) Using numpy.full() Method
In this approach, simply use numpy.full() and pass the number of rows and columns and True. It will create a matrix of all True.
Example 1: NumPy Matrix of All True or All False Using numpy.full() Method
# Import numpy
import numpy as np
# Numpy Matrix of all True
arr1 = np.full((2, 2), True)
# Numpy Matrix of all False
arr2 = np.full((2, 2), False)
# Printing
print("arr1:\n",arr1,"\n")
print("arr2:\n",arr2,"\n")
Output
arr1:
[[ True True]
[ True True]]
arr2:
[[False False]
[False False]]
2) Using numpy.ones() Method
In this approach, simply use numpy.ones() method, it returns a new array of given shape and data type, where the element's value is set to 1.
Example 2: NumPy Matrix of All True Using numpy.ones() Method
# Import numpy
import numpy as np
# Creating numpy array
arr = np.ones((2, 2), dtype=bool)
# Printing
print("arr:\n",arr,"\n")
Output
arr:
[[ True True]
[ True True]]
3) Using numpy.zeroes() Method
In this approach, simply use numpy.zeroes() method, it returns a new array of given shape and data type, where the element's value is set to 0.
Example 3: NumPy Matrix of All False Using numpy.zeroes() Method
# Import numpy
import numpy as np
# Creating numpy array
arr = np.zeros((2, 2), dtype=bool)
# Printing
print("arr:\n",arr,"\n")
Output
arr:
[[False False]
[False False]]
Python NumPy Programs »