NumPy np.identity()

One of the most practical but straightforward functions in NumPy is the identity() function. This function allows you to generate an identity array in a simple step.

Let us explore how this function works and how to use it.

What is an identity array?

Before proceeding further, it is good to clarify what an identity array is.

An identity array refers to a square array with the ones in the main diagonal. In simple terms, an identity array is an array that holds ones in the main diagonal while the rest of the elements are populated with zeros.

The above is an example of an identity array.

NumPy identity() Function Syntax

The function has a simple syntax as shown below:

numpy.identity(n, dtype=None, *, like=None)

Function Parameters

  1. n – refers to the dimensions of the output array. The order is rows and columns.
  2. dtype – specifies the data type of the output array.

Function Return Value

The function returns an identity array of the specified shape, i.e., n x n.

Example 1

Take the example shown below:

# import numpy
import numpy as np
# generate square array

The code above should generate an identity array with five rows and five columns. The resulting output is as shown:

[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]

Example 2

You can also specify the data type of the array elements to be floating-point values. An example code is shown below:

print(np.identity(3, dtype=float))

The resulting array is as shown:

[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]


Through this article, you learned what an identity array is. You also learned how to generate an identity array of the shape n x n using the NumPy identity function.

Stay tuned for more!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list