NumPy Zeros: Create Zero-Filled Arrays with np.zeros()
Updated on
Initializing arrays with zeros is one of the most common operations in numerical computing. You need pre-allocated arrays for accumulating results in loops, zero-padded matrices for image processing, placeholder tensors for neural network weights, or empty grids for simulation state. Using Python lists filled with zeros is slow and lacks the mathematical operations that NumPy provides.
np.zeros() creates arrays of any shape filled with zeros, using the data type you specify. It is fast, memory-efficient, and the standard way to initialize arrays in NumPy.
Basic Usage
1D Array
import numpy as np
# Create a 1D array of 5 zeros
a = np.zeros(5)
print(a) # [0. 0. 0. 0. 0.]
print(a.dtype) # float64 (default)
print(a.shape) # (5,)2D Array (Matrix)
import numpy as np
# 3 rows, 4 columns
matrix = np.zeros((3, 4))
print(matrix)
# [[0. 0. 0. 0.]
# [0. 0. 0. 0.]
# [0. 0. 0. 0.]]
print(matrix.shape) # (3, 4)3D Array
import numpy as np
# 2 layers, 3 rows, 4 columns
tensor = np.zeros((2, 3, 4))
print(tensor.shape) # (2, 3, 4)
print(tensor.size) # 24 elements totalSpecifying Data Types
The default dtype is float64. Use the dtype parameter to change it:
import numpy as np
# Integer zeros
int_zeros = np.zeros(5, dtype=int)
print(int_zeros) # [0 0 0 0 0]
print(int_zeros.dtype) # int64
# Boolean zeros (False)
bool_zeros = np.zeros(5, dtype=bool)
print(bool_zeros) # [False False False False False]
# Complex zeros
complex_zeros = np.zeros(3, dtype=complex)
print(complex_zeros) # [0.+0.j 0.+0.j 0.+0.j]
# 32-bit float (saves memory)
small_zeros = np.zeros((1000, 1000), dtype=np.float32)
print(f"Memory: {small_zeros.nbytes / 1024 / 1024:.1f} MB") # ~3.8 MB vs 7.6 MB for float64Common dtypes
| dtype | Description | Zeros Look Like | Memory per Element |
|---|---|---|---|
float64 | 64-bit float (default) | 0. | 8 bytes |
float32 | 32-bit float | 0. | 4 bytes |
int64 | 64-bit integer | 0 | 8 bytes |
int32 | 32-bit integer | 0 | 4 bytes |
bool | Boolean | False | 1 byte |
complex128 | 128-bit complex | 0.+0.j | 16 bytes |
np.zeros_like() -- Match an Existing Array
Create a zero array with the same shape and dtype as another array:
import numpy as np
original = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
# Same shape and dtype
zeros_copy = np.zeros_like(original)
print(zeros_copy)
# [[0. 0. 0.]
# [0. 0. 0.]]
print(zeros_copy.dtype) # float32
print(zeros_copy.shape) # (2, 3)
# Override dtype
int_copy = np.zeros_like(original, dtype=int)
print(int_copy.dtype) # int64Related Initialization Functions
| Function | Creates | Use Case |
|---|---|---|
np.zeros(shape) | All zeros | Default initialization |
np.ones(shape) | All ones | Multiplicative identity, masks |
np.full(shape, value) | All same value | Custom fill value |
np.empty(shape) | Uninitialized | Performance (when you'll fill immediately) |
np.eye(n) | Identity matrix | Linear algebra |
np.zeros_like(arr) | Zeros matching another array | Result arrays matching input |
import numpy as np
# Ones
print(np.ones((2, 3)))
# [[1. 1. 1.]
# [1. 1. 1.]]
# Full (custom value)
print(np.full((2, 3), 7))
# [[7 7 7]
# [7 7 7]]
# Empty (uninitialized -- faster but contains garbage)
empty = np.empty((2, 3)) # Contents unpredictable
# Identity matrix
print(np.eye(3))
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]Practical Use Cases
Pre-Allocate Result Arrays
import numpy as np
# Pre-allocate for performance (avoids repeated concatenation)
n_iterations = 1000
results = np.zeros(n_iterations)
for i in range(n_iterations):
results[i] = np.random.randn() ** 2
print(f"Mean: {results.mean():.4f}")
print(f"Std: {results.std():.4f}")Confusion Matrix
import numpy as np
def confusion_matrix(y_true, y_pred, n_classes):
"""Build a confusion matrix from predictions."""
cm = np.zeros((n_classes, n_classes), dtype=int)
for true, pred in zip(y_true, y_pred):
cm[true][pred] += 1
return cm
y_true = [0, 1, 2, 0, 1, 2, 0, 0, 1, 2]
y_pred = [0, 1, 1, 0, 2, 2, 0, 1, 1, 0]
cm = confusion_matrix(y_true, y_pred, 3)
print(cm)
# [[3 1 0]
# [0 2 1]
# [1 0 2]]Zero Padding for Signal Processing
import numpy as np
signal = np.array([1, 2, 3, 4, 5])
# Pad with zeros to length 16 (power of 2 for FFT)
padded = np.zeros(16)
padded[:len(signal)] = signal
print(padded)
# [1. 2. 3. 4. 5. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
# Using np.pad (more flexible)
padded2 = np.pad(signal, (0, 11), mode='constant', constant_values=0)
print(padded2)Image Processing -- Zero Padding
import numpy as np
# Original 3x3 image
image = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Add 1-pixel zero padding
padded = np.zeros((5, 5), dtype=image.dtype)
padded[1:-1, 1:-1] = image
print(padded)
# [[0 0 0 0 0]
# [0 1 2 3 0]
# [0 4 5 6 0]
# [0 7 8 9 0]
# [0 0 0 0 0]]Accumulation Pattern
import numpy as np
# Accumulate counts in a histogram
data = np.random.randint(0, 10, size=1000)
bins = np.zeros(10, dtype=int)
for value in data:
bins[value] += 1
print("Histogram:")
for i, count in enumerate(bins):
bar = '#' * (count // 5)
print(f" {i}: {bar} ({count})")Exploring Zero Arrays in Jupyter
When building numerical algorithms that use zero-initialized arrays, RunCell (opens in a new tab) provides an AI-powered Jupyter environment where you can inspect array shapes, dtypes, and memory usage interactively as you develop.
FAQ
How do I create an array of zeros in NumPy?
Use np.zeros(shape) where shape is an integer for 1D or a tuple for multi-dimensional. For example, np.zeros(5) creates [0., 0., 0., 0., 0.] and np.zeros((3, 4)) creates a 3x4 matrix of zeros. The default dtype is float64.
What is the difference between np.zeros and np.empty?
np.zeros() initializes every element to zero. np.empty() allocates memory without initialization, so it contains whatever was previously in that memory location. np.empty() is slightly faster but only safe when you will immediately fill every element before reading.
How do I create integer zeros instead of float zeros?
Pass dtype=int to np.zeros(): np.zeros(5, dtype=int) creates [0, 0, 0, 0, 0] with dtype int64. You can also use specific types like np.int32 or np.int8 for memory control.
How do I create a zero array with the same shape as another array?
Use np.zeros_like(existing_array). This copies the shape and dtype of the input array. You can override the dtype with np.zeros_like(arr, dtype=float).
Is np.zeros() faster than np.full(shape, 0)?
Yes, np.zeros() is slightly faster because it uses optimized OS-level memory allocation (calloc) that provides zeroed memory directly, while np.full() must allocate and then fill. For most practical purposes the difference is negligible.
Conclusion
np.zeros() is the standard way to create zero-filled arrays in NumPy. Use it for pre-allocation, padding, accumulation patterns, and initialization. Choose np.zeros_like() when you need to match an existing array's shape. Specify dtype to control memory usage -- float32 uses half the memory of float64. For non-zero initialization, use np.ones(), np.full(), or np.empty() depending on your needs.