While the first part of the question (which is in the title) has been answered a few times before (i.e., Why is NaN not equal to NaN?), I don't see why the second piece works the way it does (inspired by this question How to Check list containing NaN)?
Namely:
>> nan == nan
False
>> nan in [nan]
True
An explanatory addendum to the question considering the answer from @DSM. So, why float("nan")
is behaving differently from nan
? Shouldn't it evaluate again to simple nan
and why interpreter behaves this way?
>> x = float("nan")
>> y = nan
>> x
nan
>> y
nan
>> x is nan, x is float("nan"), y is nan
(False, False, True)
Basically, it refers to same generic nan
in the first case, but creates separate object in the second:
>> nans = [nan for i in range(2)]
>> map(id, nans)
[190459300, 190459300]
>> nans = [float("nan") for i in range(2)]
>> map(id, nans)
[190459300, 190459301]