I'm experimenting with NaN values and it turns out that sorting tuples containing NaN doesn't work very well.
>>> tuples = [(float('nan'), i) for i in range(7)]
... random.shuffle(tuples)
... sorted(tuples)
[(nan, 6), (nan, 0), (nan, 2), (nan, 5), (nan, 4), (nan, 3), (nan, 1)]
This kinda makes sense, considering that all comparison operations between NaN and NaN should return False, as explained in this question.
>>> float('nan') == float('nan')
False
>>> float('nan') < float('nan')
False
>>> float('nan') > float('nan')
False
However, when I change my example slightly, it is suddenly possible to sort the list of tuples.
>>> nan = float('nan')
... tuples = [(nan, i) for i in range(7)]
... random.shuffle(tuples)
... sorted(tuples)
[(nan, 0), (nan, 1), (nan, 2), (nan, 3), (nan, 4), (nan, 5), (nan, 6)]
>>> tuples # it was really shuffled
[(nan, 6), (nan, 0), (nan, 2), (nan, 3), (nan, 1), (nan, 4), (nan, 5)]
What's going on here? Why is it possible to sort the list in the second example, but not the first one?