1

I read an article that python retains some number objects for better performance. For example:

x = 3
y = 3
print(id(x))
print(id(y))

gives out same values, which means that x and y are referencing to exactly same object. The article suggested that the retained number objects are approximately in range 1~100.

So I tested following code for getting the exact range:

for i in range(-1000,1000):
    x = int(str(i))
    y = int(str(i))
    if str(id(x)) == str(id(y)):
        print(i)

and the result is quite weird: it prints out -5~256.

I'm wondering how these two magic numbers came from and why they're being used. Also, will these two values change in different environment? Thanks!

Hubert Lin
  • 97
  • 2
  • 8

1 Answers1

1

256 is a power of two and small enough that people would be using numbers to that range.

-5 I am less sure about, perhaps as special values?

Related: What's with the Integer Cache inside Python?

Also a word of wisdom from that thread:

this is an implementation detail, don't ever rely on it happening or not happening

Community
  • 1
  • 1
code11
  • 1,986
  • 5
  • 29
  • 37