0

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?

2
  • 1
    np.ndarray([0]).all() returns empty array where as np.array([0]) returns array with 0 as element. np.all() checks if there is any False i.e (0) Commented Jul 24, 2022 at 19:08
  • ndarray is a lower level constructor that we don't usually use. It's best reserved for cases where you have a preexisting data buffer. Here's it's more like np.empty. Commented Jul 24, 2022 at 20:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I assumed the signatures of ndarray and array were compatible... didn't realize the first arg to ndarray was actually a shape. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.