Open In App

NumPy – Create array filled with all ones

Last Updated : 24 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

To create an array filled with all ones, given the shape and type of array, we can use numpy.ones() method of NumPy library in Python.

import numpy as np

array = np.ones(5)
print(array) 

Output:

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

2D Array of Ones

We can also create a 2D array (matrix) filled with ones by passing a tuple to the shape parameter.

import numpy as np

# Create a 2D array of ones (3 rows, 4 columns)
ones_array_2d = np.ones((3, 4))
print(ones_array_2d)

Output
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]

Array with a Specific Data Type

We can specify the data type of the array using the dtype parameter.

import numpy as np

# Create an integer array of ones with 4 elements
ones_int_array = np.ones(4, dtype=int)
print(ones_int_array)

Output
[1 1 1 1]

Explanation:

  • By specifying dtype=int, we ensure that the array is of integer type instead of the default float64.

Multi-Dimensional Array of Ones

We can also create a higher-dimensional array (3D or more) by passing a tuple representing the shape.

import numpy as np

# Create a 3D array of ones with shape (2, 3, 4)
ones_array_3d = np.ones((2, 3, 4))
print(ones_array_3d)

Output
[[[1. 1. 1. 1.]
  [1. 1. 1. 1.]
  [1. 1. 1. 1.]]

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

Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg