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!

2
  • 1
    It's a CPython implementation detail (optimization), not Python in general. Commented Sep 22, 2016 at 13:42
  • 1
    the answer is, don't use ids for non mutable types Commented Sep 22, 2016 at 13:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.