Skip to content
Advertisement

Why is hash of nan zero?

I would have thought

>>> hash(0)
0
>>> import math
>>> hash(math.nan)
0

would lead to frequent hash collisions. Why are they both hashed to zero?

Advertisement

Answer

This behaviour has changed in Python 3.10:

  • Hashes of NaN values of both float type and decimal.Decimal type now depend on object identity. Formerly, they always hashed to 0 even though NaN values are not equal to one another. This caused potentially quadratic runtime behavior due to excessive hash collisions when creating dictionaries and sets containing multiple NaNs. (Contributed by Raymond Hettinger in bpo-43475.)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement