I used to believe that in
operator in Python checks the presence of element in some collection using equality checking ==
, so element in some_list
is roughly equivalent to any(x == element for x in some_list)
. For example:
True in [1, 2, 3]
# True because True == 1
or
1 in [1., 2., 3.]
# also True because 1 == 1.
However, it is well-known that NaN
is not equal to itself. So I expected that float("NaN") in [float("NaN")]
is False
. And it is False
indeed.
However, if we use numpy.nan
instead of float("NaN")
, the situation is quite different:
import numpy as np
np.nan in [np.nan, 1, 2]
# True
But np.nan == np.nan
still gives False
!
How is it possible? What's the difference between np.nan
and float("NaN")
? How does in
deal with np.nan
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…