Why does `is` sometimes work for numbers but fail for equal strings?
Quick answer
== compares values; is checks whether two names refer to the very same object. Use == for ordinary comparisons of numbers and strings. An is check may appear to work for equal values if Python reuses an object, but that reuse is not guaranteed. Reserve is for questions of identity, such as whether two names refer to one shared object. [S1]
The question, the details, the next step.
A practical checklist
Use
==to compare a number or string with an expected value.Use
isonly when the condition asks whether two names refer to the same object.Treat an
isresult for equal numbers or strings as incidental, not as a value-comparison guarantee.When reviewing a condition, say its intended question aloud: “equal value” or “same object?”
A few more useful answers
If two strings have identical text, does `is` always return `True`?
No. Equal string values need not be the same object, and Python does not promise reuse of particular string objects. Use == to compare their text. [S1]
When is `is` the right choice?
Use it when you specifically need to know whether two names refer to the same object, as with an alias to a shared list. It is not a substitute for comparing ordinary values.
Sources
References used for this guide.
- [S1] Built-in Types — comparison operations docs.python.org · Checked
