NumPy Tutorial NumPy Statistics NumPy Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

NumPy - identity() function



The NumPy identity() function returns the identity array. The identity array is a square array with ones on the main diagonal. The syntax for using this function is given below:

Syntax

numpy.identity(n, dtype=None)

Parameters

n Required. Specify the number of rows (and columns) in n x n output.
dtype Optional. Specify the desired data-type for the output. Default: float.

Return Value

Returns n x n array with its main diagonal set to one, and all other elements 0.

Example:

The example below shows the usage of identity() function.

import numpy as np

Arr1 = np.identity(3)
print("Arr1 is:\n", Arr1)

#specifying int data type
Arr2 = np.identity(3, dtype=int)
print("\nArr2 is:\n", Arr2)

The output of the above code will be:

Arr1 is:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Arr2 is:
[[1 0 0]
 [0 1 0]
 [0 0 1]]

❮ NumPy - Functions

5