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

Question:

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?

Answers:

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.

Answered By: sj95126
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.