np.identity(n) is a simpler, more restricted version of np.eye(n): it always produces a square matrix with the ones strictly on the main diagonal, with no equivalent of np.eye()'s M, non-square shape, or k, diagonal offset, parameters. For the common case of just needing a plain identity matrix, np.identity() communicates that specific intent slightly more directly than calling np.eye() with its extra unused parameters.
1Understanding np.identity()
np.identity(n) is a simpler, more restricted version of np.eye(n): it always produces a square matrix with the ones strictly on the main diagonal, with no equivalent of np.eye()'s M, non-square shape, or k, diagonal offset, parameters. For the common case of just needing a plain identity matrix, np.identity() communicates that specific intent slightly more directly than calling np.eye() with its extra unused parameters.
Use np.identity(n) instead of np.eye(n) specifically when you want a plain square identity matrix and nothing more — it's functionally identical to np.eye(n) with no extra arguments, but reads more directly as expressing exactly that intent.
import numpy as np
I = np.identity(4)
print(I)2Practical Example
Here is a real-world application of np.identity() showing how it is used in production NumPy code.
import numpy as np
A = np.array([[2, 0], [0, 3]])
I = np.identity(2)
print(A @ I)3Best Practices
Follow these guidelines when working with np.identity():
1. Use np.identity(n) for a plain identity matrix; switch to np.eye() only when you need its extra shape or diagonal-offset options
2. Cast to an integer dtype explicitly (dtype=int) if you need an identity matrix without floating-point representation
3. Use np.identity(n) as the starting point when iteratively building up a matrix via a sequence of linear transformations
Tip: Use np.identity(n) instead of np.eye(n) specifically when you want a plain square identity matrix and nothing more — it's functionally identical to np.eye(n) with no extra arguments, but reads more directly as expressing exactly that intent.
import numpy as np
I = np.identity(4)
print(I)