×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

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,

  1. Using numpy.full() Method
  2. Using numpy.ones() Method
  3. 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 »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.