A question I came across while learning about Python's assignment behavior.
When 10 is assigned to variables a and b as shown below,
Python
>>> a = 10
>>> b = 10
In my head, like this ↓ "** values are both 10, but two objects are born in memory, each with a and b names. ID (memory address) is of course different. It was an image of "** pointing to **". It's called Python assignment is binding / bind.
However, when I check the ID of the object referenced by the variables a and b,
Python
>>> id(a)
4343178640
>>> id(b)
4343178640
>>>
>>> a is b
True
>>>
#the same...!?!?!?
It showed exactly the same ID. As shown below, ** a and b both refer to the same object **.
If I had set b = a
, I was satisfied with this result, but I did not substitute a for b.
I searched for "python variable int id same" and it didn't come up, so I searched for "python int same address" on Google US and it was solved.
Python WAT !? Integer Cache → [Integer Objects (official document)](https://docs.python.org/3/c- api / long.html # c.PyLong_FromLong)
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. The current implementation keeps an array of integer objects for all integers from -5 to 256, and generating a number in this range actually returns a reference to an existing object. ..
So that's why
"Integers from -5 to 256 are ready to be used in memory. So when the assignment of ʻa = 10`` b = 10is performed, both variables a and b are already in memory. Just reference the integer object
10` above, and the result will be the same ID."
If you try with values of 256, 257, which is the boundary between expanded and unexpanded in memory,
Python
>>> a = 256
>>> b = 256
>>> id(a)
4343186512
>>> id(b)
4343186512 #ID is the same
>>> a is b
True
>>>
>>> a = 257
>>> b = 257
>>> id(a)
4346386992
>>> id(b)
4346387088 #ID is different! !!
>>> a is b
False
>>>
As expected from the official documentation, we can see from 257 that the objects referenced by variable a and variable b are different.
If you read the site below, the purpose is to "use numbers from -5 to 256 frequently and make them available immediately for performance". Real Python: Small Integer Caching
I was told "I try to keep an array of ** integer objects ** ~", so I tried using floating point numbers ...
Python
>>> a = 0.5
>>> b = 0.5
>>> id(a)
4317942456
>>> id(b)
4317941880 #ID is different
>>> a is b
False
>>>
The result is that the values themselves are the same, but the IDs are different for floating point numbers. I was able to confirm that this is also only an integer as documented.
Python 3.7.1