0
0
NumPydata~5 mins

np.zeros() for zero-filled arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.zeros() to create arrays filled with zeros. This helps when you need a clean starting point for calculations or data storage.

When you want to create an empty grid or matrix to fill later, like a game board.
When you need a placeholder array to store results before calculation.
When initializing weights or biases in machine learning models with zeros.
When you want to reset data to zero before starting a new process.
When you want to create a mask or filter array filled with zeros.
Syntax
NumPy
import numpy as np

array = np.zeros(shape, dtype=float, order='C')

shape can be a single number (for 1D array) or a tuple for multi-dimensional arrays.

dtype sets the type of numbers (default is float).

Examples
This creates a simple list of 5 zeros.
NumPy
import numpy as np

# Create a 1D array of 5 zeros
array_1d = np.zeros(5)
print(array_1d)
This creates a table with 3 rows and 4 columns filled with zeros.
NumPy
import numpy as np

# Create a 2D array (3 rows, 4 columns) of zeros
array_2d = np.zeros((3, 4))
print(array_2d)
This creates an empty array with no elements.
NumPy
import numpy as np

# Create an empty array with zero elements (edge case)
empty_array = np.zeros(0)
print(empty_array)
This creates a 1D array of zeros but as integers instead of floats.
NumPy
import numpy as np

# Create a 1D array of zeros with integer type
int_zeros = np.zeros(4, dtype=int)
print(int_zeros)
Sample Program

This program creates a 2x3 array filled with zeros, prints it, then changes two values and prints the updated array.

NumPy
import numpy as np

# Create a 2D zero-filled array with 2 rows and 3 columns
zero_array = np.zeros((2, 3))
print("Array before filling:")
print(zero_array)

# Fill the array with some values
zero_array[0, 0] = 10
zero_array[1, 2] = 20

print("\nArray after filling some values:")
print(zero_array)
OutputSuccess
Important Notes

Time complexity to create the array is O(n), where n is the total number of elements.

Space complexity is O(n) because it stores all zeros in memory.

Common mistake: forgetting that shape must be a tuple for multi-dimensional arrays, e.g., (3, 4), not just two numbers.

Use np.zeros() when you need a clean array to fill later. For arrays with random values, use np.random functions instead.

Summary

np.zeros() creates arrays filled with zeros for easy initialization.

You can create arrays of any shape and data type.

It is useful when you want a blank slate to store or calculate data.