Python Integer Interning: Why 256 is cached, 257 is not

What is Integer Interning in Python? Why is 256 is 256, but 257 is different in Python? Integer Interning is a memory optimisation technique used in Python. In most programs, small numbers like 0, 1, 10, -1 are used most of the times (loop counters, indexes, flags, etc.). Creating a brand new object every time would waste a lot of memory. So what Python does is this - When Python starts, it pre-creates and stores integers from -5 to 256. a = 10 → Python reuses the existing 10 b = 10 → points to the same object in memory So a is b is True. 257 is not in the pre-created pool. a = 257 → new object b = 257 → another new object Same value, different memory locations → is returns False. Note: The exact integer pool range and behaviour can differ based on Python version, implementation, and execution context. Takeaway - Using is for comparisons should be done cautiously. It checks identity, not value, and can lead to unusual bugs. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment

  • diagram

Very valuable brother ☑️

To view or add a comment, sign in

Explore content categories