Join waitlist
PythonCommunity question

a is b True for 256 but False for 257??

Asked by Fatima Siddiqui 1 month ago 2 answers 10 votes

>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False

what

2 answers

aman khan1 month agoMost voted8

CPython keeps cached int objects from -5 to 256, so every 256 is the same object. 257 gets created fresh each time in the REPL.

If you put the same code in a .py file it might print True for 257 too, because constants in one code block get reused.

Use == for values, `is` only for None.

Fatima Siddiqui1 month ago1

REPL vs file giving different answers is crazy

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.