np.zeros(shape) allocates an array of the requested shape, an integer for 1D, or a tuple for multi-dimensional arrays, and initializes every element to 0, using float64 by default unless a different dtype is given. It's the standard way to pre-allocate an array of a known size before filling it in with computed values, which is far more efficient than growing an array one element at a time, since NumPy arrays have a fixed size and any append-like operation actually allocates a brand-new array.
1Understanding np.zeros()
np.zeros(shape) allocates an array of the requested shape, an integer for 1D, or a tuple for multi-dimensional arrays, and initializes every element to 0, using float64 by default unless a different dtype is given. It's the standard way to pre-allocate an array of a known size before filling it in with computed values, which is far more efficient than growing an array one element at a time, since NumPy arrays have a fixed size and any append-like operation actually allocates a brand-new array.
Pre-allocate with np.zeros() (or np.empty()) whenever you know the final shape of an array ahead of time and plan to fill it in via indexing, instead of building it up incrementally with concatenation, which reallocates memory on every step.
import numpy as np
arr = np.zeros(5)
print(arr)2Practical Example
Here is a real-world application of np.zeros() showing how it is used in production NumPy code.
import numpy as np
matrix = np.zeros((2, 3), dtype=np.int32)
print(matrix)3Best Practices
Follow these guidelines when working with np.zeros():
1. Pre-allocate an output array with np.zeros() before filling it in a loop by index, instead of repeatedly concatenating/appending arrays
2. Specify an explicit dtype (like np.int32) when the default float64 wastes memory for data that's actually meant to be integers
3. Use np.zeros_like(other_array) instead of np.zeros(other_array.shape) when you want a zero-filled array matching another array's shape and dtype exactly
Tip: Pre-allocate with np.zeros() (or np.empty()) whenever you know the final shape of an array ahead of time and plan to fill it in via indexing, instead of building it up incrementally with concatenation, which reallocates memory on every step.
import numpy as np
arr = np.zeros(5)
print(arr)