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
CodePudding user response:
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
CodePudding user response:
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).