Skip to the solution
EasyDSA10 min read

What is the difference between '==' and 'is'?

1.1k views

The problem

Question presented to candidate: "In Python you can compare two things with == or with is. What is the difference, when do you use each, and why does is sometimes seem to work for numbers and strings?"

What a strong answer should cover:

  • == tests value equality by calling __eq__ (so a class can define it); is tests identity, whether both names point at the same object, and cannot be overridden.
  • The rule: use == for values and is only for singletons and sentinels, above all x is None (also is True / is False in rare cases, is NotImplemented, custom sentinels).
  • Why is "works" by accident: CPython caches small ints (-5 to 256), interns some strings and shares equal constants within one compiled unit, so results depend on how the value was made. Python 3.8+ warns with SyntaxWarning for is against a literal.
  • Equality protocol details: __eq__ can return NotImplemented and Python then tries the other operand, falling back to identity; without __eq__, == is identity.
  • The NaN edge case: nan == nan is False, but [nan] == [nan] and nan in [nan] are True because containers check identity first.

Code / implementation expected: Optional β€” two equal lists showing == True and is False, and x is None.

  • is
  • equality

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonValue vs identity, __eq__, why is None, and NaN in containers
PythonSmall-int cache, constant sharing, interning and the bytecode

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 2 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What are mutable and immutable types in Python?

Continue