Understanding the Difference Between Python's `is` and `==` Operators and Integer Caching
The article explains how Python's `is` operator checks object identity while `==` checks value equality, illustrates the small‑integer caching mechanism that makes integers from -5 to 256 share the same object, and shows how assignment patterns affect identity results.
In Python, the is operator tests whether two operands refer to the exact same object, whereas the == operator compares the values of the operands for equality.
Because Python pre‑allocates a pool of small integers (‑5 to 256), variables assigned these values often point to the same object, as demonstrated below:
>> a = 256<br/>>> b = 256<br/>>> a is b<br/>True<br/><br/>>> a = 257<br/>>> b = 257<br/>>> a is b<br/>False<br/><br/>>> a = 257; b = 257<br/>>> a is b<br/>TrueFor mutable objects like lists, identity and equality differ:
>> [] == []<br/>True<br/>>> [] is []<br/>FalseThe interpreter assigns the same object reference for cached integers, which can be observed with the id() function:
>> id(256)<br/>10922528<br/>>> a = 256<br/>>> b = 256<br/>>> id(a)<br/>10922528<br/>>> id(b)<br/>10922528<br/><br/>>> id(257)<br/>140084850247312<br/>>> x = 257<br/>>> y = 257<br/>>> id(x)<br/>140084850247440<br/>>> id(y)<br/>140084850247344When the same value is assigned to multiple variables on a single line, Python may reuse the cached object, but separate assignment statements create distinct objects:
>> a, b = 257, 257<br/>>> id(a)<br/>140640774013296<br/>>> id(b)<br/>140640774013296<br/><br/>>> a = 257<br/>>> b = 257<br/>>> id(a)<br/>140640774013392<br/>>> id(b)<br/>140640774013488This behavior is a specific optimization for the interactive interpreter, where each line is compiled separately; scripts executed from a .py file are compiled as a whole and do not exhibit the same identity shortcuts.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.