float("nan") in set or as key

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat May 28 20:26:07 EDT 2011


On Sun, 29 May 2011 00:41:16 +0100, MRAB wrote:

> Here's a curiosity. float("nan") can occur multiple times in a set or as
> a key in a dict:
> 
>  >>> {float("nan"), float("nan")}
> {nan, nan}

That's an implementation detail. Python is free to reuse the same object 
when you create an immutable object twice on the same line, but in this 
case doesn't. (I don't actually know if it ever does, but it could.)

And since NAN != NAN always, you can get two NANs in the one set, since 
they're unequal.


> when you write float('nan')
> 
> except that sometimes it can't:
> 
>  >>> nan = float("nan")
>  >>> {nan, nan}
> {nan}

But in this case, you try to put the same NAN in the set twice. Since 
sets optimize element testing by checking for identity before equality, 
the NAN only goes in once.


-- 
Steven



More information about the Python-list mailing list