3

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

Chrispresso
  • 3,660
  • 2
  • 19
  • 31

1 Answers1

5

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.

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • 1
    This [github issue](https://github.com/numpy/numpy/issues/5942) seems to confirm the reason: the difference is indeed because the class is efferent. – cs95 May 24 '19 at 22:27
  • Dang, I thought `np.all` was returning the same type as the `all` I'm used to. Should have checked that first. Thanks! – Chrispresso May 24 '19 at 22:28
  • @Chrispresso, you shouldn't be using `is` even with "the `all` I'm used to" - it's not testing what you actually want to test. About the only common, valid use for this operator is `X is None`. – jasonharper May 24 '19 at 22:54