About
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2025. All rights reserved.
The numpy.eye() function creates a 2-dimensional identity matrix with a specified number of rows and columns, or a square matrix with ones on the diagonal and zeros elsewhere. In this post, we will explore the various ways in which the numpy.eye() function can be used in Python.
Here is the simplest usage of the numpy.eye() function:
This program generates and prints an identity matrix of size 3x3. Thus we obtain:
You can change the size of your identity matrix easily:
with corresponding output:
Your matrix need not be a square matrix, eg;
This creates a 6x3 matrix with 1s along the diagonal (note that the diagonal has only 3 elements):
You can also use the same numpy.eye() function to place 1s at an offset to the diagonal. For this purpose you use the “k” parameter, eg:
Note that k=0 returns the same identity matrix as before. Positive values of k place the 1s to the right and above the main diagonal. Likewise, negative values of k places the 1s below and to the left of the main diagonal. The output is thus:
Thus, the numpy.eye() function is a powerful tool for creating identity matrices of various sizes and diagonal positions. It is simple to use and has several useful parameters that allow for customization.
If you liked learning about numpy.eye() learn about the numpy.diag() function!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

import numpy as np
print(np.eye(3))[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]import numpy as np
print(np.eye(5))[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]import numpy as np
print(np.eye(6,3))[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]import numpy as np
# 1s along main diagonal
print(np.eye(3,k=0))
# 1s above the diagonal, one step
print(np.eye(3,k=1))
# 1s below the diagonal, one step
print(np.eye(3,k=-1))[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]]
[[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]]