Comparing python objects can be tricky at times. Can you figure out what is going on in the above code example? Answer below:
---
When we run Python, it pre-loads a global list of integers in the range [-5, 256]. Every time an integer is referenced in this range, Python does not create a new object. Instead, it uses the cached version.
This is done for optimization purposes. It was considered that these numbers are used a lot by programmers. Therefore, it would make sense to have them ready at startup.
However, referencing any integer beyond 256 (or before -5) will create a new object every time.
In the last example, when a and b are set to 257 in the same line, the Python interpreter creates a new object. Then it references the second variable with the same object.
Share this post on LinkedIn: Post Link.
The below image should give you a better understanding:
I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn.
Check out these tips on GitHub: Daily Dose of Data Science.
Thanks Avi. Do you know if this specific behaviour being proposed to be changed in future Python versions?
Hello Avi. This happens only for integers outside the range of -5, 256?
In real world, when the value of these variables is not fixed, it forces to use 2 auxiliary variables like a2, b2 = a, b? Supposing that a and b are the variables obtained and that will be used?
What happens if the initial assignment of a and b ocurrs in separate statement and next assignments for a and b ocurr in different lines because the structure of the code? Is there a workaround? I'm starting to learn python and I come from c and learning Golang so it's a little weird.