ML Foundations

Distinguish an empty NumPy array from a scalar-shaped array

An empty shape tuple describes zero axes, not zero stored elements. Check size when testing emptiness.

Example results for Distinguish an empty NumPy array from a scalar-shaped array. scalar shape, dimensions, size: () 0 1
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Shape counts axes, while size counts elements

A zero-dimensional NumPy array has shape (), meaning its shape contains no axis lengths. That does not mean the array contains no value. Its ndim is zero while its size is one. [1, 2]

An empty one-dimensional array instead has shape (0,), ndim one and size zero. If the question is whether an array has any stored elements, use its size rather than treating an empty shape tuple as an empty array. [1, 2]

References: [1], [2]

Compare two small arrays

Run python examples/numpy_scalar_shape_and_size.py. The first array wraps the integer seven and prints shape (), zero dimensions and size one. The second is constructed from an empty list and prints shape (0,), one dimension and size zero. [1, 2]

The example reads the scalar-shaped array using an empty index tuple and verifies both dimension and size values. This separates a single scalar-shaped value from a sequence with no elements. [3]

Executed with Python 3.12.14; stdout and checksum recorded in private evidence.

import numpy as np

scalar = np.array(7)
empty = np.array([])
print('scalar shape, dimensions, size:', scalar.shape, scalar.ndim, scalar.size)
print('empty shape, dimensions, size:', empty.shape, empty.ndim, empty.size)
print('scalar value:', int(scalar[()]))
assert scalar.size == 1 and scalar.ndim == 0
assert empty.size == 0 and empty.ndim == 1

Recorded output

scalar shape, dimensions, size: () 0 1
empty shape, dimensions, size: (0,) 1 0
scalar value: 7

References: [1], [2], [3]

Check the contract before downstream processing

Size answers how many elements are present, not whether a value is valid, missing or suitable for an application. For example, an array containing a missing marker can still contain one element. Apply a separate validity check when needed.

If a downstream function requires a vector, also check ndim or normalize the shape deliberately. This fixture covers a numeric scalar and an empty one-dimensional array; it does not define a general missing-data policy. [1, 2]

References: [1], [2]

Sources

  1. NumPy ndarray size
  2. NumPy ndarray ndim
  3. NumPy indexing