Search code examples
pythonnumpylogicnumpy-ndarray

Why is numpy.ndarray([0]).all() returning True while numpy.array([0]).all() returning False?


This seems surprising to me:

import numpy as np
assert np.ndarray([0]).all()
assert not np.array([0]).all()

What is going on here?


Solution

  • Consider what those two calls produce:

    >>> np.ndarray([0])
    array([], dtype=float64)
    

    This is an empty 1-D array, because you specified a single dimension of length 0.

    >>> np.array([0])
    array([0])
    

    This is a 1-D array containing a single element, 0.

    The definition of all() isn't just "all elements are True", it's also "no elements are False", as seen here:

    >>> np.array([]).all()
    True
    

    So:

    np.ndarray([0]).all()
    

    is True because it's an empty array, while:

    np.array([0]).all()
    

    is False because it's an array of one non-True element.