NaN comparisons - Call For Anecdotes

Chris Angelico rosuav at gmail.com
Thu Jul 10 07:38:00 EDT 2014


On Thu, Jul 10, 2014 at 9:28 PM, MRAB <python at mrabarnett.plus.com> wrote:
> I can think of one place where equality of NaNs would be useful:
> sorting.
>
> However, in that use-case, you would also want it to be orderable,
> perhaps greater than any other non-NaN float.

In that case, you're setting special rules, so you probably want a
key-based sort. Since the sorting of tuples works by comparing
elements sequentially, it's simple enough:

>>> l=[1.0,2.0,1.5,float("nan"),1.7]
>>> sorted(l,key=lambda n: (n!=n, n))
[1.0, 1.5, 1.7, 2.0, nan]

I'm not sure what's supposed to happen if you just let sorted() go
with its default comparisons. It seems to put the nan at the end, but
I wouldn't bet on that being reliable, unless it's documented
somewhere. Of course, with a key sort you can choose to put NaNs at
the beginning just as easily:

>>> sorted(l,key=lambda n: (n==n, n))
[nan, 1.0, 1.5, 1.7, 2.0]

You want custom rules for sorting? You got 'em.

ChrisA



More information about the Python-list mailing list