Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty numpy array boolean contradiction [duplicate]

I accidentally found something in Numpy, which I can't really understand. If I check an empty Numpy array for any true value

    np.array([]).any()

it will evaluate to false, whereas if I check all values to be true

    np.array([]).all()

it evaluates to true. This appears weird to me since no value is true but at the same time all values are true...

like image 932
Toggo Avatar asked Apr 25 '26 19:04

Toggo


2 Answers

This isn't a bug, it returns True because all values are not equal to zero which is the criteria for returning True see the following note:

Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.

compare with the following:

In[102]:

np.array([True,]).all()
Out[102]: True

This would be equivalent to an array full of NaN which would return True

like image 76
EdChum Avatar answered Apr 28 '26 09:04

EdChum


The logic you are seeing is not specific to NumPy. This is a Python convention which has been implemented in NumPy:

  • any returns True if any value is True. Otherwise False.
  • all returns True if no value is False. Otherwise True.

See the pseuedo-code in the docs to see the logic in pure Python.

In the case of np.array([]).any() or any([]), there are no True values, because you have a 0-dimensional array or a 0-length list. Therefore, the result is False.

In the case of np.array([]).all() or all([]), there are no False values, because you have a 0-dimensional array or a 0-length list. Therefore, the result is True.

like image 25
jpp Avatar answered Apr 28 '26 09:04

jpp