Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does "ndarray.all() is False" always returns False in python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading