Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxJuniorVery commonTheory

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

Identity versus equality
Python
editable · browser sandbox
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.

#identity#equality#gotchas

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics