0

Was wondering about the logic in python. When using any() or all() on a numpy array and using is False/True I always get False, but when using "==" I get the answer I expect. So

import numpy as np
a = np.array([True,False,True])
a.any() is False 
>False
a.any() is True
>False

but this work as expected

a.any() == True
>True
a.any() == False
>False
  • Because the return value of `any` will **never** be identitcal to `True` or `False`, which are language guaranteed singltons of type `bool`, whereas `any` always returns an object of type `numpy.bool_` not `bool` – juanpa.arrivillaga Nov 24 '21 at 10:41

2 Answers2

1

The is operator is comparing if the objects are the same (have the same id). The == operator compares two values. You can see that the value is the same (True), but the id is different. See:

In [4]: id(True)
Out[4]: 140734689232720

In [5]: id(a.any())
Out[5]: 140734684830488

So what you are seeing is two different objects that have similar human readable, printed value "True". As AKX noted, these two objects are of different type: True is bool but a.any() is numpy.bool_.

Note on comparing values with booleans

As a side note, you typically would not want to compare to boolean with is, so no

if a.any() is False:
   # do something

this is a perfect example why not. In general you are interested if the values are truthy, not True. Also, there is no point in comparing to boolean even with == operator:

if a.any() == False:
   # do something

instead, a pythonic way would be to just write

if not a.any():
   # do something
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
1

Numpy operations return Numpy types.

>>> import numpy as np
>>> a = np.array([True,False,True])
>>> a.any()
True
>>> type(a.any())
<class 'numpy.bool_'>

Never use is for comparisons (unless you know you really need it, which is very rarely).

AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    Actually, you don't even need to compare a boolean to a boolean, just use the boolean directly or its negation. – mozway Nov 24 '21 at 10:25
  • Yup. Or if you need a Python `bool` for whatever reason, cast it with e.g. `bool(a.any())`. – AKX Nov 24 '21 at 10:26