3

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...

hubalazs
  • 448
  • 4
  • 13
Toggo
  • 127
  • 1
  • 7

3 Answers3

4

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

EdChum
  • 376,765
  • 198
  • 813
  • 562
  • I didn't think it was a bug. I just could not understand it. But now it makes sense. So while any() is searching for true's all() is searching for false's. Thank you for your help... – Toggo Jul 18 '18 at 12:40
  • I think the possible dupe: https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work explains the behaviour, so I think this is the convention that `numpy` is following, we could mark this as a dupe but let's see if others agree – EdChum Jul 18 '18 at 12:40
3

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

This is a normal behavior.

It is not possible to find a value that is true, so np.array([]).any() is False

For every value in the array, this value is False (It is easy to check, because there are no values in the array, so you don't have to check anything).

Gelineau
  • 2,031
  • 4
  • 20
  • 30