-1

Can anyone tell me why looking for the minimum value in a list using min(list) is not working when NaN is the first element of the list? The same applies when using max(list)

import math

y = [float('nan'),1,2,3,0,float('nan'),6,7,8,9]
print(y)
print(math.isnan(y[0]))
print(min(y))


w = [10,1,2,3,0,float('nan'),6,7,8,9]
print(w)
print(min(w))
print(math.isnan(w[5]))
Tola
  • 254
  • 3
  • 17

2 Answers2

3

Any comparison operation performed on nan with a number will return False.

print(y[1] > y[0])
print(y[1] < y[0])

Results in

False
False

If the built-in function follows the same logic while comparing the elements the above behavior is easily explained. If the first element is selected as min element any comparison afterward will be False hence returning nan as min element.

som
  • 71
  • 4
-1

You can filter y or w to ignore nan:

print(min(i for i in y if not math.isnan(i)))
# 0
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • 4
    while this is true, I don't think it answer's OP's question regarding _why_ it doesn't work, which has to do with how python compares elements to NaN – wpercy Jan 22 '20 at 16:55