What is the difference between `is` and `==`, and when should each be used?
Answer
`is` compares object identity — whether two names point to the exact same object in memory — while `==` compares value equality by calling `__eq__`, which a class can override. Use `is` for singleton comparisons such as `x is None`, `x is True` or comparing against sentinel objects, and use `==` for comparing the actual data two variables hold. Relying on `is` for value comparison of numbers or strings is unreliable because it depends on implementation-specific interning.
Strong answer includes
- identity versus value equality
- is for None/singleton checks
- interning makes is unreliable for values
Practical example
Python
Result
Run the code to see the result.
== asks whether values are equal; is asks whether two names reference the exact same object. Singleton checks such as None should use is.
Expected result: True, False, True, True.