Arrays - ones() and zeros()

NumPy - The Basics

1 min read

Published Sep 22 2025, updated Aug 17 2026


11
0
0
0

NumPyPython

What They Do

  • numpy.zeros() → creates an array filled with 0s.
  • numpy.ones() → creates an array filled with 1s.
  • 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 is float.



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 all 0s.
  • Use np.ones() → when you need an array of all 1s.
    Both are quick and essential for initialising arrays in numerical computing.
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact
NumPy - The Basics | Arrays - ones() and zeros() | SimpleSteps.guide