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...
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With