0 views
In Python, why use `is None` rather than `== None`; what is the correct way to check for NaN?
Asked at
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.
Also asked at Цифровые технологии и платформы
Similar questions
- What is the difference between `is` and the equality operator (`==`)?
- Tell me how dict works in Python.
- Does Python have tools for checking types (statically or at runtime) to get closer to strict typing, and which ones have you worked with?
- What is the difference between NaN and None in Python?
- How is a Python dictionary (dict) implemented under the hood, and what is the time complexity of its basic operations?