NumPy eye() Function

numpy.eye() is used to create a 2-D array (matrix) with 1s on the diagonal and 0s everywhere else.

numpy.eye(N, M=None, k=0, dtype=float)

Parameters

Parameter Meaning
N Number of rows
M Number of columns. If omitted, M = N
k Diagonal position
dtype Data type of the array

1. Basic Example

import numpy as np a = np.eye(3) print(a)

Output:

[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]

This creates a 3 × 3 identity matrix.

2. dtype

By default, values are float.

a = np.eye(3, dtype=int) print(a)

Output:

[[1 0 0] [0 1 0] [0 0 1]]

3. Different Rows and Columns

a = np.eye(3, 5, dtype=int) print(a)

Output:

[[1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0]]

Here:
N = 3 → rows
M = 5 → columns
So the result is 3 × 5.

4. Important: k Parameter

k controls which diagonal gets the 1s.

  • k = 0 → Main diagonal
np.eye(4, dtype=int)
[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]
  • k = 1 → Above the main diagonal
np.eye(4, k=1, dtype=int)
[[0 1 0 0] [0 0 1 0] [0 0 0 1] [0 0 0 0]]
  • k = -1 → Below the main diagonal
np.eye(4, k=-1, dtype=int)
[[0 0 0 0] [1 0 0 0] [0 1 0 0] [0 0 1 0]]
Easy way to remember:
       k = -2
         ↓
      k = -1
         ↓
0  1  0  0  0
1  0  1  0  0   ← k = 0 is this main diagonal
0  1  0  1  0
0  0  1  0  1
0  0  0  1  0
         ↑
       k = +1

In short:

np.eye(3) # 3×3 identity matrix np.eye(3, 4) # 3×4 matrix np.eye(3, dtype=int) # integer values np.eye(4, k=1) # diagonal above main diagonal np.eye(4, k=-1) # diagonal below main diagonal

eye() is particularly useful when teaching identity matrices, diagonal matrices, linear algebra, and matrix operations in NumPy.


NumPy identity() Function

np.identity() creates a square identity matrix — a matrix having 1 on the main diagonal and 0 everywhere else.

np.identity(n, dtype=None)

1. Basic Example

import numpy as np a = np.identity(3) print(a)

Output:

[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]

Here 3 means 3 rows × 3 columns.

2. Using dtype

By default, the values are float.

a = np.identity(4, dtype=int) print(a)

Output:

[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]

identity() vs eye()

Important point:

Feature np.identity() np.eye()
Square matrix ✅ Always ❌ Not necessarily
Rows n N
Columns n M (optional)
Main diagonal 1 1
k parameter ❌ No ✅ Yes

Example

np.identity(3)

Always gives:

[[1 0 0] [0 1 0] [0 0 1]]

Whereas:

np.eye(3, 5)

can create:

[[1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0]]

And:

np.eye(4, k=1, dtype=int)

can move the diagonal:

[[0 1 0 0] [0 0 1 0] [0 0 0 1] [0 0 0 0]]
Student-friendly rule:
identity() = square identity matrix only
eye() = more flexible identity/diagonal matrix

np.identity(5) is essentially a convenient way to create a 5 × 5 identity matrix.

NumPy diag() Function

np.diag() is used for two different purposes:

  1. Create a diagonal matrix from a 1-D array/list.
  2. Extract the diagonal from a 2-D matrix.
np.diag(v, k=0)

1. Create a diagonal matrix

import numpy as np a = np.diag([10, 20, 30]) print(a)

Output:

[[10 0 0] [ 0 20 0] [ 0 0 30]]

The values become the main diagonal.

2. Extract diagonal from a matrix

a = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) print(np.diag(a))

Output:

[10 50 90]

So:

10 20 30 40 50 60 70 80 90 ↑ ↑ 10 → 50 → 90

3. k parameter

k specifies which diagonal to use.

  • Main diagonal — k=0
np.diag([1, 2, 3], k=0)
[[1 0 0] [0 2 0] [0 0 3]]
  • Above main diagonal — k=1
np.diag([1, 2, 3], k=1)
[[0 1 0 0] [0 0 2 0] [0 0 0 3] [0 0 0 0]]
  • Below main diagonal — k=-1
np.diag([1, 2, 3], k=-1)
[[0 0 0 0] [1 0 0 0] [0 2 0 0] [0 0 3 0]]

diag() vs eye() vs identity()

Function Purpose
np.identity(3) 3×3 identity matrix
np.eye(3) Identity-like matrix, more flexible
np.diag([10,20,30]) Create diagonal matrix with 10,20,30
np.diag(matrix) Extract diagonal from matrix
Easy memory trick:
  • np.identity(3)     → Only 1s on diagonal
  • np.eye(3, k=1)     → 1s on selected diagonal
  • np.diag([10,20,30])  → Your values on diagonal
  • np.diag(matrix)    → Get diagonal values from matrix

NumPy fromfunction() and fromfile()

Both functions are used to create NumPy arrays, but their purposes are different.

  • np.fromfunction() creates an array by applying a function to array indices.
  • np.fromfile() creates an array by reading data from a text or binary file.

1. NumPy fromfunction()

The np.fromfunction() function creates an array by executing a function on the indices of each element.

np.fromfunction(function, shape, dtype=float)
Parameter Description
function Function used to generate values
shape Dimensions of the output array
dtype Data type of the coordinate arrays passed to the function

Example 1: Create a 1-D array

import numpy as np a = np.fromfunction(lambda i: i * 2, (5,), dtype=int) print(a)

Output:

[0 2 4 6 8]

Explanation:

Index (i) Formula (i*2) Result
00 × 20
11 × 22
22 × 24
33 × 26
44 × 28

The function receives the indices, not existing array values.

Example 2: Create a 2-D array

a = np.fromfunction( lambda i, j: i + j, (3, 4), dtype=int ) print(a)

Output:

[[0 1 2 3] [1 2 3 4] [2 3 4 5]]

How does it work?

  • i represents the row index.
  • j represents the column index.
  • (3,4) creates three rows and four columns.
  • Each element is calculated using i+j.

For example:

a[0][0] = 0 + 0 = 0 a[0][1] = 0 + 1 = 1 a[1][2] = 1 + 2 = 3 a[2][3] = 2 + 3 = 5

Example 3: Multiplication table

a = np.fromfunction( lambda i, j: (i+1)*(j+1), (5, 5), dtype=int ) print(a)

Output:

[[ 1 2 3 4 5] [ 2 4 6 8 10] [ 3 6 9 12 15] [ 4 8 12 16 20] [ 5 10 15 20 25]]

This creates a multiplication table without explicitly writing a Python loop.

Example 4: Create even and odd patterns

a = np.fromfunction( lambda i, j: (i+j)%2, (4, 4), dtype=int ) print(a)

Output:

[[0 1 0 1] [1 0 1 0] [0 1 0 1] [1 0 1 0]]

This is useful for generating a checkerboard pattern.

Example 5: Using a normal function instead of lambda

import numpy as np def calculate(i, j): return i * 10 + j a = np.fromfunction(calculate, (3, 3), dtype=int) print(a)

Output:

[[ 0 1 2] [10 11 12] [20 21 22]]
Important: fromfunction() normally calls the supplied function once with coordinate arrays. It does not call the Python function separately for every element.

2. NumPy fromfile()

The np.fromfile() function reads data from an existing file and converts it into a NumPy array.

It supports two formats:

  1. Text files
  2. Binary files
np.fromfile(file, dtype=float, count=-1, sep='')
Parameter Description Default
file File name or file object Required
dtype Data type float
count Number of elements to read -1 (all)
sep Separator between text values '' (binary mode)

Example 1: Read numbers from a text file

Suppose we have a file named numbers.txt.

File content:

10 20 30 40 50

Python:

import numpy as np a = np.fromfile("numbers.txt", sep=" ", dtype=int) print(a)

Output:

[10 20 30 40 50]
Important: sep=" " tells NumPy to read whitespace-separated text values. Without sep, NumPy uses binary mode.

Example 2: Read comma-separated values

File: marks.txt

78,85,90,67,88

Python:

a = np.fromfile( "marks.txt", dtype=int, sep="," ) print(a)

Output:

[78 85 90 67 88]

Example 3: Using count

File: numbers.txt

10 20 30 40 50 60 70

Python:

a = np.fromfile( "numbers.txt", dtype=int, sep=" ", count=4 ) print(a)

Output:

[10 20 30 40]

Only four elements are read.

Example 4: Convert file data into a 2-D array

File: data.txt

10 20 30 40 50 60 70 80 90

Python:

a = np.fromfile("data.txt", dtype=int, sep=" ") print(a)

Output:

[10 20 30 40 50 60 70 80 90]

Notice that fromfile() returns a 1-D array. To convert it into a matrix:

a = a.reshape(3, 3) print(a)

Output:

[[10 20 30] [40 50 60] [70 80 90]]

Example 5: Write and read binary data

First, create a binary file:

import numpy as np a = np.array([10, 20, 30, 40, 50], dtype=np.int32) a.tofile("numbers.bin")

Now read the file:

b = np.fromfile("numbers.bin", dtype=np.int32) print(b)

Output:

[10 20 30 40 50]
The data type must match the binary file's representation. For portable NumPy storage, np.save() and np.load() are generally preferable because they preserve array shape and dtype information.

3. Difference Between fromfunction() and fromfile()

Feature fromfunction() fromfile()
PurposeGenerate array using functionRead array from file
Existing file requiredNoYes
Lambda supportedYesNot applicable
Shape parameterYesNo
Supports multidimensional outputYesReturns 1-D
Main useMathematical patternsFile data loading
InputFunction and shapeFile path

4. Practice Questions ✍️

fromfunction()
  1. Create a 1-D array containing squares of numbers from 0 to 9.
  2. Create a 4×4 matrix where each element is i+j.
  3. Create a 5×5 multiplication table.
  4. Create a 3×3 matrix containing i*i+j*j.
  5. Create a 5×5 matrix with 1 at even row-column index sums and 0 elsewhere.
fromfile()
  1. Create a text file containing 10 integers and read them into a NumPy array.
  2. Read only the first five values from a file.
  3. Read comma-separated marks from a text file.
  4. Read nine numbers from a file and reshape them into a 3×3 matrix.
  5. Save a NumPy array to a binary file using tofile() and read it using fromfile().