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
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 with0
s.numpy.ones()
→ creates an array filled with1
s.- 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)
Copy to Clipboard
- 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 zeros
np.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 ones
np.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]]
Copy to Clipboard
Toggle show comments
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 all0
s. - Use
np.ones()
→ when you need an array of all1
s.
Both are quick and essential for initialising arrays in numerical computing.