Chrispresso
Chrispresso

Reputation: 4071

Why does np.all return the wrong value when I use "is" compared to "=="?

So I tracked down a bug in my code and can reproduce is with the following. Basically I need to check if all elements in an np.ndarray are not 0.

>>> a = np.ones((3,3))
>>> np.all(a == 0) == False
True

Okay perfect, all values within a are non-zero. I know I can also do np.all((a == 0) == False) instead to explicitly ask to be compared to 0 but I didn't at first and this is made me realize there is a difference when comparing is to == in the False case.

>>> np.all(a == 0) is False
False

I know that is should compare if the objects point to the same object. But does this mean that my two values that returned False don't actually point to the same False? I may just be overthinking this though...

Upvotes: 2

Views: 357

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375585

The return type is numpy.bool_ rather than bool:

In [11]: type(np.all(a == 0))
Out[11]: numpy.bool_

In [12]: type(False)
Out[12]: bool

The is check asserts that two objects point to the same object.

Upvotes: 4

Related Questions