The identity() function is defined under the Numpy library that can be imported as an **import numpy**. We can create multidimensional arrays and derive other mathematical statistics with the help of NumPy. In today’s article, let’s see what is identity array or matrix is and how to create it.

**np.identity**

The **np**.**identity()** is a numpy library function that returns the **identity** **array**, the number of rows (and columns) in n x n output. The **identity** **array** is a square array with ones on the main diagonal.

**Syntax**

numpy.identity(N, dtype=<class 'float'>)

**Parameters**

**N:**It represents the number of rows or columns in a 2D array.**dtype:**It denotes the data type of returned array. It is entirely optional, and by default, it is float.

**Return Value**

The **numpy.identity()** method returns a 2D array of shapes, N x N, i.e., a matrix where all elements are equal to zero, except for the main diagonal, whose values are equal to one.

**Example Programs**

**Write a python program to show the working of the NumPy.identity() method.**

import numpy as np # 2x2 matrix with 1's on main diagnol a = np.identity(2, dtype=float) print("Matrix a : \n", a) # 3x3 matrix with 1's on main diagonal b = np.identity(3) print("\nMatrix b : \n", b) # 3x3 matrix with 1's on main diagonal with string datatype c = np.identity(3, dtype=str) print("\nMatrix c : \n", c) # 3x3 matrix with 1's on main diagonal with int datatype d = np.identity(3, dtype=int) print("\nMatrix d : \n", d)

**Output**

Matrix a : [[1. 0.] [0. 1.]] Matrix b : [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] Matrix c : [['1' '' ''] ['' '1' ''] ['' '' '1']] Matrix d : [[1 0 0] [0 1 0] [0 0 1]]

**Explanation**

In the 1st function number of rows and columns was 2. So, a matrix of 2 X 2 was displayed, having its main diagonal with value 1 with return type as a float. Here, float values were returned as the identity function has float return type by default.

In the 2nd function number of rows was 3, and the column was 3. So, a matrix of 3 X 3 was displayed, having its main diagonal as 1 with return type as a float.

The 3rd function number of rows was 3, and the column was 3, so a matrix of 3 X 3 was displayed, having its main diagonal as 1 with return type as a string. And other values were initialized to empty characters, which depict values equal to zero.

In the 4th function number of rows was 3, and the column was 3. So, a matrix of 3 X 3 was displayed, having its main diagonal as 1 with return type as int.

That’s it for the **np.identity() **method.