Arrays - ones() and zeros()
NumPy - The Basics
1 min read
This section is 1 min read, full guide is 14 min read
Published Sep 22 2025, updated Aug 17 2026
11
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
NumPyPython
What They Do
numpy.zeros()→ creates an array filled with0s.numpy.ones()→ creates an array filled with1s.- Both functions let you specify the shape and optionally the data type of the array.
Function Signatures
numpy.zeros(shape, dtype=float)numpy.ones(shape, dtype=float)- shape → tuple or int defining array dimensions.
- dtype → (optional) set the type of elements (e.g.,
int,float,complex). Default isfloat.
Examples
import numpy as np# 1D array of zerosnp.zeros(5)# → [0. 0. 0. 0. 0.]# 2D array of zeros (3 rows, 4 columns)np.zeros((3, 4))# → # [[0. 0. 0. 0.]# [0. 0. 0. 0.]# [0. 0. 0. 0.]]# 1D array of onesnp.ones(5)# → [1. 1. 1. 1. 1.]# 2D array of ones (2x3)np.ones((2, 3))# → # [[1. 1. 1.]# [1. 1. 1.]]# Specify data type (integers instead of floats)np.zeros((2, 2), dtype=int)# → # [[0 0]# [0 0]]np.ones((2, 2), dtype=int)# → # [[1 1]# [1 1]]Key Use Cases
- Initializing placeholder arrays for computations.
- Creating masks or matrices for linear algebra, machine learning, or simulations.
- Serving as a base before filling arrays with other values.
In short
- Use
np.zeros()→ when you need an array of all0s. - Use
np.ones()→ when you need an array of all1s.
Both are quick and essential for initialising arrays in numerical computing.