Comparing lists containing NaNs
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 Question
01:16 Accepted answer (Score 2)
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/3916...
Question links:
[Why in numpy ]: https://stackoverflow.com/questions/2032...
[Why is NaN not equal to NaN? [duplicate]]: https://stackoverflow.com/questions/1003...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #comparison #nan
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 Question
01:16 Accepted answer (Score 2)
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/3916...
Question links:
[Why in numpy ]: https://stackoverflow.com/questions/2032...
[Why is NaN not equal to NaN? [duplicate]]: https://stackoverflow.com/questions/1003...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #comparison #nan
#avk47
ACCEPTED ANSWER
Score 4
To understand what happens here, simply replace nan = np.nan by foo = float('nan'), you will get exactly the same result, why?
>>> foo = float('nan')
>>> foo is foo # This is obviously True!
True
>>> foo == foo # This is False per the standard (nan != nan).
False
>>> bar = float('nan') # foo and bar are two different objects.
>>> foo is bar
False
>>> foo is float(foo) # "Tricky", but float(x) is x if type(x) == float.
True
Now think that numpy.nan is just a variable name that holds a float('nan').
Now why [nan] == [nan] is simply because list comparison first test identity equality between items before equality for value, think of it as:
def equals(l1, l2):
for u, v in zip(l1, l2):
if u is not v and u != v:
return False
return True