np.eye(N) creates an N by N identity matrix — ones along the main diagonal, zeros elsewhere — which is the multiplicative identity for matrix multiplication, analogous to the number 1 for regular multiplication. Passing M creates a non-square N by M matrix instead, and the k parameter shifts which diagonal gets the ones: k=0 is the main diagonal, the default, positive k shifts it above the main diagonal, and negative k shifts it below, which is useful for constructing certain banded or shifted matrix patterns beyond a plain identity matrix.
1Understanding np.eye()
np.eye(N) creates an N by N identity matrix — ones along the main diagonal, zeros elsewhere — which is the multiplicative identity for matrix multiplication, analogous to the number 1 for regular multiplication. Passing M creates a non-square N by M matrix instead, and the k parameter shifts which diagonal gets the ones: k=0 is the main diagonal, the default, positive k shifts it above the main diagonal, and negative k shifts it below, which is useful for constructing certain banded or shifted matrix patterns beyond a plain identity matrix.
Use np.identity(n) instead of np.eye(n) when you specifically want a plain, square identity matrix and nothing else — it's a slightly more direct, readable way to express that specific intent, since np.eye()'s extra M and k parameters aren't needed.
import numpy as np
identity = np.eye(3)
print(identity)2Practical Example
Here is a real-world application of np.eye() showing how it is used in production NumPy code.
import numpy as np
shifted = np.eye(4, k=1)
print(shifted)3Best Practices
Follow these guidelines when working with np.eye():
1. Use np.eye(n) (or np.identity(n)) whenever an algorithm calls for the identity matrix, rather than manually constructing it with zeros and manual diagonal assignment
2. Use the k parameter to build shifted-diagonal matrices for specialized linear algebra patterns, instead of manually indexing and assigning each diagonal element
3. Reach for np.diag() instead of np.eye() when you need a diagonal matrix with arbitrary values on the diagonal, not just ones
Tip: Use np.identity(n) instead of np.eye(n) when you specifically want a plain, square identity matrix and nothing else — it's a slightly more direct, readable way to express that specific intent, since np.eye()'s extra M and k parameters aren't needed.
import numpy as np
identity = np.eye(3)
print(identity)