w3resource

NumPy: Create an array of ones and an array of zeros

NumPy: Array Object Exercise-34 with Solution

Write a NumPy program to create an array of ones and an array of zeros.

Sample Solution:-

Python Code:

import numpy as np
print("Create an array of zeros")
x = np.zeros((1,2))
print("Default type is float")
print(x)
print("Type changes to int")
x = np.zeros((1,2), dtype = np.int)
print(x)
print("Create an array of ones")
y= np.ones((1,2)) 
print("Default type is float")
print(y)
print("Type changes to int")
y = np.ones((1,2), dtype = np.int)
print(y)

Sample Output:

Create an array of zeros                                               
Default type is float                                                  
[[ 0.  0.]]                                                            
Type changes to int                                                    
[[0 0]]                                                                
Create an array of ones                                                
Default type is float                                                  
[[ 1.  1.]]                                                            
Type changes to int                                                    
[[1 1]]

Python Code Editor:

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

Previous: Write a NumPy program to find the memory size of a NumPy array.
Next: Write a NumPy program to change the dimension of an array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}