#395·wtfpython

nans and object identity

Author: sjmilliusCreated Nov 27, 2025Updated Dec 18, 2025
Labelsnew snippets

Description

nans (like float("nan"), np.nan) follow the IEEE 754 standard for floating-point arithmetic, which specifies that NaN is not equal to anything, including itself, so:

python
np.nan == np.nan  # False
float("nan") == float("nan") # False

But

python
np.nan is np.nan  # True

So these are objects that are not equal but identical to themselves. This leads to unexpected results in cases where object identity is taken as a short cut before equality comparisons, e.g. in tuples.

Snippet preview

python
>>> import numpy as np
>>> np.nan == np.nan
False
>>> (np.nan, np.nan) == (np.nan, np.nan)
True
>>> nan1 = float('nan'); nan2 = float('nan')
>>> nan1 == nan2
False
>>> (nan1, nan2) == (nan1, nan2)
True
>>> (nan1, nan2) == (nan2, nan1)
False

Checklist before calling for maintainers

  • Have you checked to ensure there aren't other open Issues for the same update/change?
  • Have you checked that this snippet is not similar to any of the existing snippets?
  • Have you added an Explanation section? It shall include the reasons for changes and why you'd like us to include them