np.ones: Understanding numpy ones() Function

Python NumPy ones() Function Example

The numpy.ones() function returns the new array of given shape and data type, where the element’s value is set to 1. The ones() function is very similar to numpy zeros() function.


The np.ones() is a Numpy library function that returns an array of similar shape and size with values of elements of the array as ones. The np.ones() function takes three parameters at max and returns an array with element values as ones.

The ones() function is defined under numpy, which can be imported as import numpy as np. We can create multidimensional arrays and derive other mathematical statistics with the help of numpy, a library in Python.


numpy.ones(shape, dtype, order) 


It takes three parameters, out of which one parameter is optional. 

The first parameter is the shape; it is an integer or a sequence of integers. 

The second parameter is the order, representing the order in the memory, such as C_contiguous or F_contiguous. 

The third parameter is optional and is the datatype of the returning array. By default, it is float.

Return Value

NumPy ones() function returns an array with element values as ones.

Example programs on ones() method in Python

Write a program to show the working of ones() function in Python.

import numpy as np

arr1 = np.ones([2, 2], dtype=int)
print("Matrix arr1 : \n", arr1)

arr2 = np.ones([3, 3], dtype=int)
print("\nMatrix arr2 : \n", arr2)


Matrix arr1 :
 [[1 1]
 [1 1]]

Matrix arr2 :
 [[1 1 1]
 [1 1 1]
 [1 1 1]]

In this example, we can see that by taking an array and using ones(), we get all the matrix values as 1.

Write a program to take only 1 row with 4 elements and use the ones() function.

See the following code.

import numpy as np

arr1 = np.ones(4, dtype=int)
print("Matrix arr1 : \n", arr1)


Matrix arr1 :
 [1 1 1 1]

In the above example, we can see that just passing 4 as the first parameter, and we get a single row with 5 elements than by using ones(), we fix every element value as 1.

See also

Numpy triu()

Numpy tril()

Numpy tri()

Numpy empty_like()

Numpy empty()

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.