Shape and size checks
Validate expected tensor or matrix dimensions before processing.
NumPy · Pipe
ndarray.size gives the total number of elements in an array. It equals the product of the array’s dimensions and returns a standard arbitrary-precision Python integer.
Accessing an array’s size returns the total number of elements across all dimensions. It is equivalent to multiplying the dimensions in shape, but size returns a standard arbitrary-precision Python integer.
a.sizeimport numpy as np
array = np.zeros((3, 5, 2), dtype=np.complex128)
print(array.size) # 30
print(np.prod(array.shape)) # 30Creates a three-dimensional array and reads its total element count with the size attribute.
Validate expected tensor or matrix dimensions before processing.
Allocate, reshape, or report data using the total element count.
Avoid fixed-width integer concerns when using counts in later calculations.
ndarray.size is an attribute containing the total number of elements in the array. For an array with shape (3, 5, 2), its value is 30.
Follow-up: How can the total be derived from shape? Multiply all dimensions together; this is equivalent to np.prod(a.shape).
The total is the product of the array’s dimensions, so size equals np.prod(a.shape). It counts elements across every axis rather than along only one axis.
Follow-up: How would you count elements along one axis instead? Use the documented np.size function with its axis argument, rather than ndarray.size.
a.size returns a standard arbitrary-precision Python integer. An alternative such as np.prod(a.shape) returns a NumPy integer type, so their types can differ even when their numeric values match.
Follow-up: Why can that type difference matter? A fixed-size integer result can be vulnerable to overflow in later calculations, whereas the standard Python integer avoids that limitation.
numpy.ndarray.shapenumpy.prodnumpy.size