4 ms·
That was weird. Makes sense once you know about NaN's incomparability, but still surprising. I had to try it in Python (3.10.4, Windows on x86), it worked fine
by unwind 4y ago
That was weird. Makes sense once you know about NaN's incomparability, but still surprising.
I had to try it in Python (3.10.4, Windows on x86), it worked fine:
>>> import math
>>> a={math.nan: 1}
>>> a
{nan: 1}
>>> del(a[math.nan])
>>> a
{}
- vhcr 4y agoThis works as expected only because id(math.nan) is always the same, if you build the nan dynamically, it will fail: >>> d = {float('nan'): 1} >>> d {nan: 1} >>> del d[float('nan')] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: nan
- masklinn 4y agoIt's because cpython shortcuts through identity: https://github.com/python/cpython/blob/main/Objects/object.c#L724-L731 https://github.com/python/cpython/blob/main/Objects/object.c... /* Quick result when objects are the same. Guarantees that identity implies equality. */ if (v == w) { if (op == Py_EQ) return 1; else if (op == Py_NE) return 0; } `math.nan` is always itself, and thus this shortcut is taken and the key works.
- deleted 4y ago[deleted]