# Return the identity array in Numpy

NumpyServer Side ProgrammingProgramming

To return the identity array, use the numpy.identity() method in Python Numpy. The identity array is a square array with ones on the main diagonal. The 1s parameter is the number of rows (and columns) in n x n output. The function returns n x n array with its main diagonal set to one, and all other elements 0.

The like parameter is a reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

## Steps

At first, import the required library −

import numpy as np

Create a 2d array. To return the identity array, use the numpy.identity() method in Python Numpy. The identity array is a square array with ones on the main diagonal. The 1s parameter is the number of rows (and columns) in n x n output −

arr = np.identity(4)


Display the array −

print("Array...\n", arr)

Get the type of the array −

print("\nArray type...\n", arr.dtype)


Get the shape of the array −

print("\nArray shape...\n", arr.shape)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)


Get the number of elements in the Array −

print("\nArray (count of elements)...\n",arr.size)

## Example

import numpy as np

# Create a 2d array
# To return the identity array, use the numpy.identity() method in Python Numpy
# The identity array is a square array with ones on the main diagonal.
# The 1s parameter is the number of rows (and columns) in n x n output
arr = np.identity(4)

# Display the array
print("Array...\n", arr)

# Get the type of the array
print("\nArray type...\n", arr.dtype)

# Get the shape of the array
print("\nArray shape...\n", arr.shape)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the number of elements of the Array
print("\nArray (count of elements)...\n",arr.size)

## Output

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

Array type...
float64

Array shape...
(4, 4)

Array Dimensions...
2

Array (count of elements)...
16