2

When I check for equality and identity of Python operands e.g. a = []; b = a I get this:

a == b => True
a is b => True

and I understand it.

so, why I am getting diff result with np.nan?:

a = np.nan; b = a 
a == b => False
a is b => True

?

naivepredictor
  • 898
  • 4
  • 14

1 Answers1

7

Because NaN is never equal to anything else, and we use == for performing an equality comparison.

On the other hand the object used to represent NaN is identical to itself, because is is used for doing an identity comparison.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    Interesting. (+1) I tried a similar experiment with `None` instead of `np.nan`. Turns out that `a = None; b = a; print (a == b)` prints `True`. – fountainhead Mar 08 '19 at 14:02
  • Can you explain to me the difference between an equality and an identity comparison? – Psychotechnopath Apr 03 '20 at 08:47
  • 1
    @Psychotechnopath Equality: two objects with the same _value_, not necessarily the same object. Identity: the exact, same object. – Óscar López Apr 03 '20 at 08:54
  • So basically NaN == NaN returns False because it is never equal to anything else, but all np.nan's do point to the same object, and thus np.nan is np.nan returns True? This is exactly the opposite way it is in normal objects (e.g. `a = [1,2,3]` `c = [1,2,3]` `a ==c` returns `True` whereas `a is c` returns `False` – Psychotechnopath Apr 03 '20 at 08:58
  • @Psychotechnopath NaN is a special case. Nothing is equal to NaN, ever: not even NaN itself. `np.nan == np.nan` is `False`, even though `np.nan is np.nan` is `True`. – Óscar López Apr 03 '20 at 09:00
  • yes but `np.nan is np.nan` returns True, is that because they point to the same object? – Psychotechnopath Apr 03 '20 at 09:01
  • 1
    You said it yourself – Óscar López Apr 03 '20 at 09:02
  • @ÓscarLópez get it now then =) TYVM for quick response! – Psychotechnopath Apr 03 '20 at 09:03