MiddleCodeCommonNot answered yet
What does this is vs == integer test print?
Predict both lines for these integer comparisons.
a = 256; b = 256
c = 257; d = 257
print(a is b, c is d)
print(a == b, c == d)
Determine the output and explain.
True False then True True. CPython caches small integers from −5 to 256, so a and b are the same object (is → True); 257 is outside that range, so c and d are distinct objects (is → False). == compares value and is always True. Use is only for identity (e.g. x is None).
- ✗Using
isto compare integer values instead of== - ✗Believing equal integers are always the same object
- ✗Thinking
==delegates tois
- →Why does CPython cache the integers from −5 to 256?
- →When is using
isthe correct choice instead of==?