NumPy - Create array filled with all ones
Last Updated :
19 Sep, 2025
To create an array filled with all ones in Python, NumPy provides the numpy.ones() function. You can specify the shape and data type of the array.
Example: This example creates a simple 1D array of ones with 5 elements.
Python
import numpy as np
arr = np.ones(5)
print(arr)
Syntax
numpy.ones(shape, dtype=None, order='C')
Parameters:
- shape (int or tuple): Defines size of array.
- dtype (optional): Sets data type of elements.
- order (optional): Memory layout, 'C' -> Row-wise (default, C-style) and 'F' -> Column-wise (Fortran-style).
2D Array of Ones
We can also create a 2D array (matrix) filled with ones by passing a tuple to the shape parameter.
Example: This example creates a 2D matrix of ones with 3 rows and 4 columns.
Python
import numpy as np
arr = np.ones((3, 4))
print(arr)
Output[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
Explanation:
- The argument (3, 4) defines the shape of the array.
- The resulting array has 3 rows and 4 columns, filled entirely with 1.0 (float).
Array with a Specific Data Type
We can specify the data type of the array using the dtype parameter.
Example: This example creates a 1D integer array of ones with 4 elements.
Python
import numpy as np
arr = np.ones(4, dtype=int)
print(arr)
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.
Example: This example creates a 3D array of ones with shape (2, 3, 4).
Python
import numpy as np
arr = np.ones((2, 3, 4))
print(arr)
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.]]]
Explanation:
- The argument (2, 3, 4) creates a 3D array.
- It has 2 blocks, each containing a 3x4 matrix, filled with 1.0.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice