Initialize working storage
Preallocate a numeric buffer before filling it in iterative or vectorized code.
NumPy · Function
Creates a new NumPy array with a specified shape and type, initializing every element to zero. The shape, dtype, memory order, implementation reference, and device can be selected.
Call np.zeros with either one integer or a tuple describing each dimension. It allocates an ndarray with that shape, fills every element with zero, and lets you choose the element type and memory layout; the optional like and device arguments can direct array creation through compatible array implementations and devices.
numpy.zeros(shape, dtype=None, order='C', *, device=None, like=None)| Name | Type | Description |
|---|---|---|
shape | int or tuple of ints | Shape of the new array; provide an integer or a tuple of integers. |
dtype | data-type, optional | Element data type. If omitted, the default is numpy.float64. |
order | {'C', 'F'}, optional | Memory layout for multidimensional data: C-style or Fortran-style. |
like | array_like, optional | Reference object whose array type determines creation behavior when supported. |
device | str, optional | Device on which to place the array, when supported by the selected array implementation. |
out — ndarray: A new array of zeros with the requested shape, dtype, order, and applicable creation options.
import numpy as np
values = np.zeros((2, 3), dtype=np.int32)
print(values)
print(values.dtype, values.shape)Creates a 2-by-3 integer array whose elements are all zero.
Preallocate a numeric buffer before filling it in iterative or vectorized code.
Create model inputs, masks, counters, or parameter arrays with known dimensions.
Request integer or smaller-width elements to match an API or reduce storage.
Create arrays compatible with another array implementation through like.
np.zeros creates and returns a new ndarray with the requested shape, dtype, and order, with every element initialized to zero. The shape may be a single integer or a tuple of dimensions.
Follow-up: How would you ensure compact integer storage? Pass an integer dtype such as np.int32 or np.int8 explicitly.
The default dtype is numpy.float64. Passing dtype=np.int32, for example, produces integer zeros instead of floating-point zeros.
Follow-up: What changes if the dtype is structured? The returned array uses that structured dtype, so each zero-filled record contains fields initialized according to the dtype.
order selects C-style row-major or Fortran-style column-major storage for multidimensional arrays. It affects memory organization and can matter for interoperability or performance.
Follow-up: When should order be specified? Specify it when a downstream operation or external library expects a particular contiguous layout; otherwise the default C order is usually sufficient.
numpy.onesnumpy.emptynumpy.fullnumpy.zeros_like