w3resource
w3resource logo
Python Exercises

Python NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere

Python NumPy: Array Object Exercise-42 with Solution

Write a Python program to create a 3-D array with ones on the diagonal and zeros elsewhere.

Pictorial Presentation:

Python NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere

Sample Solution:-

Python Code:

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

Sample Output:

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

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create an array of 10's with the same shape and type of an given array.
Next: Write a Python program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.