ProgrammingBackend/Python Developer

Explain the semantics of the is operator and the == operator in Python. What is the difference between them and when is the use of each critical? Provide examples of typical traps.

Pass interviews with Hintsage AI assistant

Answer

  • is compares the identity of objects (i.e., whether the variables point to the same memory location).
  • == (operator eq) compares values, i.e., whether the objects are equal in terms of their content.

is should be used for comparing identity (for example, with None or for singleton objects), not for checking equality of values.

Example:

a = [1, 2, 3] b = [1, 2, 3] print(a == b) # True print(a is b) # False c = None d = None print(c is d) # True

When working with small integers or strings, the interpreter may use "interning" (cached objects), which sometimes makes is true for equal values, but this should not be used in program logic.


Trick Question

Question: What will the following code output?

a = 256 b = 256 print(a is b) c = 257 d = 257 print(c is d)

Why?

Answer: For values from -5 to 256, Python uses an integer pool. Values in this range always point to the same objects, so a is b will yield True. 257 is already outside the pool, so c is d will be False (the objects are independent).


History

Example 1

In one microservice, string equality was checked using is instead of ==. Due to interpreter optimizations, the program worked "stably" in tests but started failing after recompilation or other environment changes.


Example 2

One developer used the is operator for comparing numbers instead of ==. This worked for small numbers (thanks to the pool), but for larger ones, it failed and produced unpredictable results, causing incorrect calculations.


Example 3

In the design of an authorization system, the incoming JSON was checked using is None (correctly), and then similarly, it was done for strings: if status is "ok". This turned out to be a mistake — sometimes the condition was not met, leading to incorrect data processing logic.