Why Do Some Larger Integers in Python Appear to Be Interned?

0
7
Asked By CuriousCat42 On

Hey everyone! I'm trying to wrap my head around Python's integer interning feature. So, as we know, integers between -5 and 256 are interned by default for memory efficiency. That means when I declare two variables, like a = 10 and b = 10, they actually point to the same memory address, and 'a is b' returns True.

However, I get confused when I use larger numbers. For example, when I assign c = 1000 and d = 1000, I expect 'c is d' to return False since 1000 is outside of the interning range. But I've noticed it sometimes returns True, especially in online interpreters or specific environments. Can anyone help clarify why this is happening? Thanks!

3 Answers

Answered By SyntaxSniffer On

Just a heads up: when sharing code snippets, make sure to indent them with four spaces in forums like this! It helps with readability.

Answered By DevGuruX On

Also, keep in mind that behavior can differ between compiled Python code and the REPL. Just because you’re using the same Python version doesn’t mean the optimizations will be the same. It's one of those quirks that can lead to unexpected results!

CuriousCat42 -

Thanks for the tip! It makes sense that environments would behave differently.

Answered By CodingWizard99 On

It's interesting you mention that! Python doesn't strictly limit interning to just the range of -5 to 256. Depending on various factors, like optimization settings, Python can decide to intern larger integers. So sometimes, it might treat 1000 as a candidate for interning, which is why 'c is d' can return True.

QuestionAsker -

I see! But what about 257? I tried 'print(257 is 257)' and it returned False. Isn't that a small enough number to be interned?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.