12 Ideas to Help You Make Money From Home During the Coronavirus Pandemic

In the wake of the novel coronavirus outbreak and associated shutdowns and shelter in place orders, more Americans than ever have found themselves out of work, underemployed, or in dire need of some…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




3 Facts of the Integer Caching in Python

Understand some confusing results made by Python

Python has a special feature called integer caching, or integer interning. Sometimes, it may make us confused. For example, if we run the following code on a Python shell, the results are surprising:

Why 256 is 256 but 257 is not 257? Anything wrong?

And this is not the weirdest part yet, if we put the same code into a file and run it as a Python script, the results will surprise us again!

We put all the code into the above script called “test.py”. Then open a terminal and run the script:

😱 What? The statement x is y becomes True at this time.

If you are confused about these as well, no worries at all. This article will demystify how the integer caching feature works and summary it into three facts. After reading, you will not be confused about it anymore.

Actually, in order to save time and memory costs, Python always pre-loads all the small integers in the range of [-5, 256]. When a new integer variable in this range is declared, Python just references the cached integer to it and won’t create any new object.

In other words, all the integers in [-5, 256] are singletons and they’ve been already saved in the memory. We cannot create a new integer object in this range.

Therefore, the explanations of the first example are obvious:

Add a comment

Related posts:

Festival Essentials Checklist

Here is the complete checklist of everything you will need in order to have a good time at your next Festival. If you have any other suggestions that should be included in our range of festival…

Migratory Notes 50

Today marks one year since the first Migratory Notes went out in the aftermath of the original travel ban. At the time we thought we had created a pop-up immigration newsletter that would help make…

10 Popular Programming Languages for Every Level of Coder

As the world of software design and development continously evolves, the languages and tools used to create these apps and sites are being updated and perfected. Today, we’ll be looking at 10 of the…