mediumConceptEntryMidSenior
Why does `is` agree with `==` for some numbers and strings but not others?
5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup
Answer
Short answer
Because is compares identity while == compares value, and CPython reuses objects for small integers and for compile-time string constants. The agreement is an implementation detail of the interpreter you happen to be running, so code that relies on it works until the values change.
Was this answer helpful?
Likely follow-ups
- Why does `float('nan') in [float('nan')]` behave differently depending on how you build the list?
- When is `sys.intern` worth calling deliberately, and what does it cost you?
- Why is `is None` the correct test but `is True` usually the wrong one?
- How can a class make `==` and `is` disagree in a way that breaks a dict lookup?
Related questions
- If you override equals but not hashCode, what breaks and when?mediumAlso on immutability4 min
- A list of a million small objects uses far more memory than the data inside them. Where is it going?mediumAlso on cpython5 min
- How would you design a ledger so that any balance can always be proved?hardAlso on immutability5 min
- How would you design a thread-safe component, and why is adding synchronized to every method not a design?hardAlso on immutability7 min