Arrays - ones() and zeros()

NumPy - The Basics

1 min read

Published Sep 22 2025


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 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]]




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.

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact