Daily Dose of Data Science

Share this post

Why 256 is 256 But 257 is not 257?

www.blog.dailydoseofds.com

Why 256 is 256 But 257 is not 257?

Avi Chawla
Dec 4, 2022
6
3
Share
Share this post

Why 256 is 256 But 257 is not 257?

www.blog.dailydoseofds.com

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:

Thanks for reading Daily Dose of Data Science! Subscribe for free to receive new posts and support my work.


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.

6
3
Share
Share this post

Why 256 is 256 But 257 is not 257?

www.blog.dailydoseofds.com
Previous
Next
3 Comments
PABLO LEWIN
Dec 6, 2022

Thanks Avi. Do you know if this specific behaviour being proposed to be changed in future Python versions?

Expand full comment
Reply
PABLO LEWIN
Dec 4, 2022

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.

Expand full comment
Reply
1 reply by Avi Chawla
1 more comment…
Top
New
Community

No posts

Ready for more?

© 2023 Avi Chawla
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing