← Back to NumPy Course | Chapter 2: Creating Arrays | Lesson 5 of 7

np.eye()

np.eye() builds an identity matrix: ones along the diagonal and zeros everywhere else.

In this page:

  1. np.eye()
Syntax
python
np.eye(n)
np.eye(rows, cols, k=offset)

np.eye()

The identity matrix is the matrix equivalent of the number 1: multiplying by it changes nothing. np.eye(n) gives an n by n identity; np.identity(n) is similar. The k argument shifts the diagonal up or down.

Note: np.diag can build a matrix from your own diagonal values.

Example: np.eye()

python
import numpy as np

print(np.eye(3))
print(np.eye(3, k=1, dtype=int))

# Output:
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]
# [[0 1 0]
#  [0 0 1]
#  [0 0 0]]
Related Topics
Common Mistakes
  1. Passing a shape tuple instead of an integer size
  2. Forgetting the result is float by default
  3. Confusing eye with ones
Chapter Summary
  • eye(n) makes an identity matrix
  • k shifts the diagonal
  • Default dtype is float
  • Multiplying by identity leaves a matrix unchanged
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.