Open In App

NumPy - Create array filled with all ones

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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.

Python
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.

Python
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.

Python
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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy