w3resource logo
Python Exercises

Python NumPy: Create a 5x5 matrix with row values ranging from 0 to 4

Python NumPy: Array Object Exercise-64 with Solution

Write a Python program to create a 5x5 matrix with row values ranging from 0 to 4.

Sample Solution:-

Python Code:

import numpy as np
x = np.zeros((5,5))
print("Original array:")
print(x)
print("Row values ranging from 0 to 4.")
x += np.arange(5)
print(x)

Sample Output:

Original array:                                                        
[[ 0.  0.  0.  0.  0.]                                                 
 [ 0.  0.  0.  0.  0.]                                                 
 [ 0.  0.  0.  0.  0.]                                                 
 [ 0.  0.  0.  0.  0.]                                                 
 [ 0.  0.  0.  0.  0.]]                                                
Row values ranging from 0 to 4.                                        
[[ 0.  1.  2.  3.  4.]                                                 
 [ 0.  1.  2.  3.  4.]                                                 
 [ 0.  1.  2.  3.  4.]                                                 
 [ 0.  1.  2.  3.  4.]                                                 
 [ 0.  1.  2.  3.  4.]]

Python Code Editor:

import numpy as np
x = np.zeros((5,5))
print("Original array:")
print(x)
print("Row values ranging from 0 to 4.")
x += np.arange(5)
print(x)

Improve this sample solution and post your code through Disqus