Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
To make an identity matrix in NumPy, call np.identity(n), which returns an n × n array with 1 on the main diagonal and 0 everywhere else; np.eye(N, M=None, k=0) does the same job and also builds rectangular arrays and shifted diagonals. Both return floating-point arrays unless you pass a dtype, so np.identity(3) gives [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]. This guide shows the exact signatures from the NumPy reference, a worked check on a small matrix, and the pitfalls that matter when you use identity matrices in analysis code.
What an identity matrix is used for in research code
An identity matrix is the matrix that leaves another matrix unchanged under multiplication. The NumPy documentation for numpy.matmul shows this directly: multiplying b = [[4, 1], [2, 2]] by a = [[1, 0], [0, 1]] returns [[4, 1], [2, 2]]. In analysis scripts that property gives you three practical uses.
- A reference for checking an inverse. The documentation for
numpy.linalg.invdefines the inverse by the relationa @ ainv = ainv @ a = eye(a.shape[0]), so an identity matrix is the target you compare a computed product against. - A neutral element when you build a matrix expression. Starting a running product from an identity array means the first multiplication does not change the result. See matrix multiplication in NumPy for the
@operator andnp.matmul. - A test fixture. Because the expected output of multiplying by an identity matrix is known in advance, it is a convenient input for unit tests of functions that accept matrices.
If you work in MATLAB as well as Python, the same object is created there with eye; the MATLAB identity matrix guide covers that syntax, and the MATLAB inverse matrix guide covers the matching inverse check.
Install or access NumPy
The NumPy project’s installation page (numpy.org/install) gives pip install numpy as the standard route. To keep a project’s dependencies separate, it also shows creating a virtual environment first. On macOS and Linux:
python -m venv my-envsource my-env/bin/activatepip install numpy
On Windows the activation line is my-envScriptsactivate. If you use conda, the same page lists conda create -n my-env, then conda activate my-env, then conda install numpy. To confirm the install, run:
import numpy as npprint(np.__version__)
Record the printed version in your project notes. The signatures below are from the current stable reference; two of the optional arguments carry version notes (like was added to identity in NumPy 1.20.0, and device was added to eye in NumPy 2.0.0), so a very old environment may not accept them.
Step-by-step: create an identity matrix with np.identity and np.eye
Step 1: Import NumPy
import numpy as np
Step 2: Create a square identity matrix with np.identity
The reference gives the signature numpy.identity(n, dtype=None, *, like=None). The argument n is an integer giving the number of rows and columns of the output. The function returns an n × n array with ones on the main diagonal and zeros elsewhere.
I3 = np.identity(3)print(I3)# [[1. 0. 0.]# [0. 1. 0.]# [0. 0. 1.]]
Step 3: Create the same matrix with np.eye, or something different
The signature is numpy.eye(N, M=None, k=0, dtype=float, *, order='C', device=None, like=None). N is the number of rows; M is the number of columns and defaults to N; k is the index of the diagonal, where 0 is the main diagonal, a positive value is an upper diagonal and a negative value is a lower diagonal. The result has shape (N, M). The reference’s own examples are:
np.eye(2, dtype=np.int_) # [[1, 0], [0, 1]]np.eye(3, k=1) # [[0., 1., 0.], [0., 0., 1.], [0., 0., 0.]]
The documentation lists identity under See also as an “(almost) equivalent function”. Use np.identity when you want a plain square identity matrix and np.eye when you need a non-square shape or an offset diagonal. The data table below compares the three construction routes from the reference pages.
Step 4: Choose the data type
The default is floating point: the eye signature shows dtype=float, and the identity reference describes the data type as float by default. Pass an integer type if you want integers, as in the np.eye(2, dtype=np.int_) example above. In a numerical pipeline the float default is usually what you want, because the matrix will be combined with float arrays from measured data.
Step 5: Use it in a calculation
Multiplication with the @ operator, which numpy.matmul implements (PEP 465), leaves the other matrix unchanged:
b = np.array([[4, 1], [2, 2]])np.matmul(np.identity(2), b) # [[4., 1.], [2., 2.]]
The documentation example uses an integer identity array and returns [[4, 1], [2, 2]]; with the default float identity the values are the same but print as floats.
Worked example: checking a matrix inverse against the identity
The most common research use is verifying that a computed inverse really is an inverse. The NumPy reference for numpy.linalg.inv uses this matrix:
from numpy.linalg import inva = np.array([[1., 2.], [3., 4.]])ainv = inv(a)# [[-2. , 1. ],# [ 1.5, -0.5]]np.allclose(a @ ainv, np.eye(2)) # True
The check uses np.allclose, not ==. Floating-point arithmetic rarely reproduces an exact identity, so a comparison with a tolerance is the appropriate test. np.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False) returns True when absolute(a - b) ≤ (atol + rtol * absolute(b)) holds element-wise. Its documentation warns that the default atol is not appropriate when the reference values have magnitude much smaller than one. For an identity comparison the reference values are 1 and 0, and the zero entries are compared on the absolute tolerance, so the default atol of 1e-08 is the figure to keep in mind when you report how strict the check was. The NumPy allclose guide explains the tolerance rule in more detail. By contrast, np.array_equal requires the same shape and exactly equal elements, which is why it is the wrong tool for an inverse check.
Output and how to read it
Printing an identity matrix shows 1. on the diagonal and 0. elsewhere when the dtype is float, and 1 and 0 when it is an integer type. Three properties are worth confirming when you inspect the output:
- Shape.
np.identity(n).shapeis(n, n).np.eye(N, M)has shape(N, M), and whenN != Mork != 0the result is not a square identity matrix in the usual sense. - Diagonal position. With
k = 1the ones sit on the first diagonal above the main one, as thenp.eye(3, k=1)example shows. Onlyk = 0gives ones on the main diagonal. - Product with another matrix. Multiplying by a correctly sized identity matrix returns the other matrix. If you need the transpose of the result before multiplying, see the NumPy transpose guide; an identity matrix equals its own transpose.
Troubleshooting
The product a @ inv(a) is not exactly the identity matrix
This is expected in floating-point arithmetic. Compare with np.allclose and choose atol deliberately, as above.
inv raises LinAlgError
According to the numpy.linalg.inv reference, a LinAlgError is raised if the input is not square or if the inversion fails; a singular matrix is the standard failure. The identity matrix itself is always safe to invert, so the error points to your input data, not to the identity matrix you compare against.
inv raises nothing but the product is not close to the identity
The same reference documents an ill-conditioned example, a = [[2, 4, 6], [2, 0, 2], [6, 8, 14]], for which inv raises no error yet a @ inv(a) is not the identity matrix. The documentation’s remedy is to examine the condition number with numpy.linalg.cond; for that example it reports about 8.66e17, and notes the value may vary. cond(x, p=None) defines the condition number as the norm of x times the norm of its inverse, using the 2-norm by default. A very large value means the inverse should not be trusted, so run the cond check before relying on a computed inverse in a result you intend to publish.
ImportError when importing NumPy
The NumPy install page points to the project’s troubleshooting page for ImportError: numpy.org/doc/stable/user/troubleshooting-importerror.html. The usual first step is to confirm that the environment you activated is the one running your script.
An unexpected diagonal or shape from np.eye
If the ones are not where you expect, check k and M. Calling np.eye(3, k=1) gives an offset diagonal and np.eye(2, 3) gives a 2 × 3 array. If you wanted a square identity matrix, use np.identity(n), which has no such arguments to get wrong.
Alternatives within NumPy
NumPy itself is free to install. Besides np.identity and np.eye, the numpy.diag function can build a diagonal array from a vector. The table lists what each route does according to its reference page.
| Route | What it builds | When it fits |
|---|---|---|
np.identity(n) |
Square n × n array, ones on the main diagonal | You only need a standard identity matrix |
np.eye(N, M, k) |
(N, M) array with ones on the k-th diagonal | You need rectangular shape, an offset diagonal, memory order or a specific dtype |
np.diag(v, k) |
For a 1-D input v, a 2-D array with v on the k-th diagonal | You need other values on the diagonal; passing a vector of ones gives ones on that diagonal |
Frequently asked questions
What is the difference between np.identity and np.eye?
np.identity(n) takes one size and always returns a square array with ones on the main diagonal. np.eye takes N, an optional M, a diagonal index k, a dtype, a memory order of ‘C’ or ‘F’, and (in NumPy 2.0.0 and later) a device argument that must be “cpu” if passed. NumPy’s own reference calls identity an “(almost) equivalent function”.
Does np.identity return integers or floats?
Floats by default. Pass dtype=int to np.identity, or dtype=np.int_ to np.eye, to get integers.
How do I check that a matrix times its inverse is the identity?
Compute a @ np.linalg.inv(a) and compare it with np.eye(a.shape[0]) using np.allclose. Also check np.linalg.cond(a), because an ill-conditioned matrix can be inverted without an error and still give an inaccurate result.
Is there a NumPy identity matrix for non-square shapes?
Use np.eye(N, M). The result has ones on the main diagonal and zeros elsewhere, but it is not square, so it is not an identity matrix in the strict sense.
Sources
- NumPy documentation, numpy.identity: numpy.org/doc/stable/reference/generated/numpy.identity.html (read 2026-11-14)
- NumPy documentation, numpy.eye: numpy.org/doc/stable/reference/generated/numpy.eye.html (read 2026-11-14)
- NumPy documentation, numpy.linalg.inv: numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html (read 2026-11-14)
- NumPy documentation, numpy.linalg.cond: numpy.org/doc/stable/reference/generated/numpy.linalg.cond.html (read 2026-11-14)
- NumPy documentation, numpy.matmul: numpy.org/doc/stable/reference/generated/numpy.matmul.html (read 2026-11-14)
- NumPy documentation, numpy.allclose, numpy.array_equal and numpy.diag, same reference section (read 2026-11-14)
- NumPy installation instructions: numpy.org/install (read 2026-11-14)
Data: NumPy routines for building identity and diagonal arrays: signature and options
Compares numpy.identity, numpy.eye and numpy.diag by signature, output shape, default data type and supported options, compiled from the stable NumPy reference pages.
| Routine | Signature | Output shape | Default dtype | Diagonal offset k | Memory order option |
|---|---|---|---|---|---|
| numpy.identity | identity(n, dtype=None, *, like=None) | (n, n) | float | No | No |
| numpy.eye | eye(N, M=None, k=0, dtype=float, *, order='C', device=None, like=None) | (N, M) | float | Yes | Yes ('C' or 'F') |
| numpy.diag | diag(v, k=0) | 2-D array when v is 1-D | Not specified | Yes | No |
Sources
- numpy.identity (accessed 2026-11-14)
- numpy.eye (accessed 2026-11-14)
- numpy.diag (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







