The numpy.zeros() function returns a new ndarray of specified shape and data type, initialized entirely with zeros.
Memory Preallocation & Performance: Preallocating arrays using np.zeros() eliminates resizing overhead. Define geometries with shape tuples, set precision with dtype, or clone arrays via zeros_like(). For alternative fills, see numpy.ones() and numpy.full().
The numpy.zeros() function accepts array dimensions and optional configuration parameters:
# Formal syntax of numpy.zeros()
numpy.zeros(shape, dtype=float, order='C', *, like=None)
| Parameter | Type | Default | Description & Operational Rule |
|---|---|---|---|
shape |
int or tuple of ints |
Required | Shape of the new array (e.g., 4 for 1D, (3, 4) for 2D). |
dtype |
data-type | numpy.float64 |
Desired numerical data type (e.g., int, float, bool). |
order |
{'C', 'F'} |
'C' |
Memory layout in RAM: 'C' (row-major) or 'F' (column-major). |
like |
array_like | None |
Reference object for non-NumPy array creation. |
| Return | ndarray |
N/A | Zero-filled array with the specified shape, dtype, and memory order. |
Passing an integer creates a 1D vector; passing a tuple defines multi-dimensional axes:
Shape (3, 4): 3 Rows, 4 Columns
Shape (4, 3): 4 Rows, 3 Columns
# 1. 1D vector, 2D matrix, and 3D tensor initialization
import numpy as np
vec = np.zeros(4) # 1D vector of 4 floats
mat = np.zeros((3, 4)) # 2D matrix (3 rows x 4 cols)
cube = np.zeros((2, 3, 2), dtype=int) # 3D tensor (2x3x2)
print("1D Vector: ", vec)
print("2D Matrix:\n", mat)
print("3D Tensor shape:", cube.shape)Terminal Output:
1D Vector: [0. 0. 0. 0.]
2D Matrix:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
3D Tensor shape: (2, 3, 2)
numpy.zeros() defaults to 64-bit floats (float64). Specify custom precision with dtype:
# 2. Specifying dtypes: int, bool, complex, and string
import numpy as np
z_int = np.zeros(3, dtype=int) # Integer 0
z_bool = np.zeros(3, dtype=bool) # Boolean False
z_cplx = np.zeros(3, dtype=complex) # Complex 0. + 0.j
z_str = np.zeros(3, dtype='<U5') # Empty strings
print("Integer: ", z_int)
print("Boolean: ", z_bool)
print("Complex: ", z_cplx)
print("String: ", z_str)Terminal Output:
Integer: [0 0 0]
Boolean: [False False False]
Complex: [0.+0.j 0.+0.j 0.+0.j]
String: ['' '' '']
The order parameter specifies row-major ('C') or column-major ('F') physical memory layout:
# 3. Storage layout: Row-Major ('C') vs. Column-Major ('F')
import numpy as np
c_arr = np.zeros((3, 3), order='C')
f_arr = np.zeros((3, 3), order='F')
print("C-contiguous (row-major): ", c_arr.flags['C_CONTIGUOUS'])
print("F-contiguous (column-major):", f_arr.flags['F_CONTIGUOUS'])Terminal Output:
C-contiguous (row-major): True
F-contiguous (column-major): True
Use numpy.zeros_like() to allocate a zero array mirroring an existing array shape and dtype:
# 4. Mirroring prototype arrays with numpy.zeros_like()
import numpy as np
source = np.array([[10, 20, 30], [40, 50, 60]], dtype=np.int16)
cloned = np.zeros_like(source)
print("Source shape and dtype:", source.shape, source.dtype)
print("Mirrored zero array:\n", cloned)Terminal Output:
Source shape and dtype: (2, 3) int16
Mirrored zero array:
[[0 0 0]
[0 0 0]]
NumPy provides specialized constructors depending on your initialization needs:
| Function | Initial Contents | Speed | When to Use |
|---|---|---|---|
np.zeros() |
All zeros (0.0 or 0) |
Fast | Accumulators, image masks, zero padding. |
np.ones() |
All ones (1.0 or 1) |
Fast | Unit weights, normalization bases. |
np.full() |
Arbitrary scalar fill value | Fast | Sentinel constants (e.g. -1 or NaN). |
np.empty() |
Uninitialized memory | Fastest | Arrays immediately overwritten in loops. |
Preallocating an image mask canvas buffer:
# 5. Production Recipe: Preallocated Image Mask / Canvas Buffer
import numpy as np
# 720p grayscale canvas buffer (height=720, width=1280)
canvas = np.zeros((720, 1280), dtype=np.uint8)
# Draw centered bounding box of white pixels (255)
canvas[200:500, 400:800] = 255
print("Canvas shape: ", canvas.shape)
print("Active mask pixels: ", np.count_nonzero(canvas))Terminal Output:
Canvas shape: (720, 1280)
Active mask pixels: 120000Creating a sliding window accumulator buffer:
# 6. Production Recipe: Sliding Window Accumulator
import numpy as np
def sliding_averages(data: list, k: int) -> np.ndarray:
"""Preallocates zero array for moving averages."""
out = np.zeros(len(data) - k + 1, dtype=np.float64)
for i in range(len(out)):
out[i] = np.mean(data[i : i + k])
return out
signal = [12.0, 14.0, 11.0, 18.0, 17.0, 16.0]
print("Smoothed averages:", np.round(sliding_averages(signal, 3), 2))Terminal Output:
Smoothed averages: [12.33 14.33 15.33 17. ]
Pass multi-dimensional shapes as a single tuple rather than separate arguments:
# 7. Common traps: Tuple shape omission
import numpy as np
# Trap: Passing separate ints instead of tuple raises TypeError
try:
np.zeros(3, 4)
except TypeError as err:
print("Caught TypeError:", err)
# Correct: Pass dimensions as a tuple (3, 4)
correct = np.zeros((3, 4))
print("Correct shape: ", correct.shape)Terminal Output:
Caught TypeError: Cannot interpret '4' as a data type
Correct shape: (3, 4)
Practice zero-array creation and buffer allocation in our companion notebook:
Run interactive cells, test 2D/3D shapes, benchmark memory order, and run assertions.
View on GitHub Run in Google ColabRun unit assertions to verify numpy.zeros() mechanics:
# 8. Self-verifying unit test suite for numpy.zeros()
import numpy as np
# Test 1: 1D vector shape and zero values
v = np.zeros(5)
assert v.shape == (5,) and np.all(v == 0.0)
# Test 2: Multi-dimensional int matrix
m = np.zeros((3, 4, 2), dtype=int)
assert m.shape == (3, 4, 2) and m.size == 24
assert m.dtype == int and np.all(m == 0)
# Test 3: zeros_like matching shape and dtype
proto = np.ones((2, 5), dtype=np.float32)
z = np.zeros_like(proto)
assert z.shape == (2, 5) and z.dtype == np.float32
assert np.all(z == 0)
print("All numpy.zeros() unit assertions successfully verified!")Terminal Output:
All numpy.zeros() unit assertions successfully verified!
The default dtype is numpy.float64 (floating-point zeros 0.0).
The 2nd argument is dtype. Pass multi-dimensional shapes as a single tuple: np.zeros((3, 4)).
np.zeros() clears all memory bits to 0, whereas np.empty() allocates uninitialized RAM buffer.
Use np.zeros_like(array) to automatically copy shape and data type.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.