Arrays using zeros() and ones()

We can use the zeros() function to create an array with all zeros. The ones() function is useful to create an array with all 1s. They are written in the following format:

zeros(n, datatype)

ones(n, datatype)

where 'n' represents the number of elements. we can eliminate the 'datatype' argument. If we do not specify the 'datatype', then the default datatype used by numpy is 'float'. See the examples:

zeros(5)

This will create an array with 5 elements all are zeros, as: [0. 0. 0. 0. 0.]. If we want this array in integer format, we can use 'int' as datatype, as:

zeros(5, int)

this will create an array as: [0 0 0 0 0].

If we use ones() function, it will create an array with all elements 1. For example,

ones(5, float)

will create an array with 5 integer elements all are 1s as: [1. 1. 1. 1. 1.].

Arrays example using zeros() and ones()

A Python program to create arrays using zeros() and ones().

CopiedCopy Code

from numpy import * 
a = zeros(5, int) 
print(a) 
b = ones(5) 
#default datatype is float 
print(b)
from numpy import * 
a = zeros(7) 
print(a) 
b = ones(6,int) 
print(b)