The Python Oracle

Comparing lists containing NaNs

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------


Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping

--

Chapters
00:00 Comparing Lists Containing Nans
00:56 Accepted Answer Score 4
01:35 Thank you

--

Full question
https://stackoverflow.com/questions/3916...

--

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