Skip to content
Middle+0 views

In Python, why use `is None` rather than `== None`; what is the correct way to check for NaN?

Practice

AI answer

None is the only singleton object, so it should be checked by identity: x is None or x is not None. This does not call a user-defined __eq__ and does not depend on how a class overrides comparison. == None checks equality and may produce unexpected results.

For NaN, use a NaN check: math.isnan(x) for Python numbers, numpy.isnan(x) for NumPy arrays; in pandas, pd.isna(x) is usually used because it also accounts for None and NaT. NaN is not equal even to itself: float('nan') == float('nan') returns False, so == is not suitable for this purpose.