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);istests identity, whether both names point at the same object, and cannot be overridden.- The rule: use
==for values andisonly for singletons and sentinels, above allx is None(alsois True/is Falsein 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 withSyntaxWarningforisagainst a literal. - Equality protocol details:
__eq__can returnNotImplementedand Python then tries the other operand, falling back to identity; without__eq__,==is identity. - The NaN edge case:
nan == nanis False, but[nan] == [nan]andnan 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.