Python unexpected behaviour pt. 2: sorting NaNs


Consider this snippet:

arr = [float('NaN'), 3, 2, 1]
sorted(arr)

It will show:

[nan, 1, 2, 3]

Then:

arr = [3, 2, 1, float('NaN')]
sorted(arr)
[1, 2, 3, nan]

NaN is never sorted. This is because every comparison to float('NaN') returns False:

print(float('NaN') >= 1)
print(float('NaN') > 1)
print(float('NaN') < 1)
print(float('NaN') <= 1)
print(float('NaN') == 1)
False
False
False
False
False

Now, not only it is not sorted, it might cause python's sorted to behave rather strangely:

arr = [float('NaN'), 3, 2, float('NaN'), 1, 4, float('NaN'), 3, 2, 1]
sorted(arr)

will print

[nan, 1, 2, 3, nan, 1, 2, 3, 4, nan]

Depending on use case it might be best to check for and remove any NaNs and also make sure to check user input for it when using float(user_data).

Anyhow, I guess this is a pretty exotic behavior and it's good to know about it!