Could someone explain why my variable x returns to it's former ID after these steps:
>>> x = 10
>>> id(x)
497834400
>>> x = str(x)
>>> id(x)
48840576
>>> x = int(x)
>>> id(x)
497834400
Could someone explain why my variable x returns to it's former ID after these steps:
>>> x = 10
>>> id(x)
497834400
>>> x = str(x)
>>> id(x)
48840576
>>> x = int(x)
>>> id(x)
497834400
Python caches the integers from [-5, 256]
, which means that (during the same runtime) a integer in the above range will always have the same id
.
Because 10 is something called small-integer in python. Python will cache the small-integer between [-5,257)in a pool called "small_ints". So the instance of integer in [-5,257) are all shared in whole python, that's why id(10) always return the same address.
What is the number returned from the function id() ?
It is "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime." (Python Standard Library - Built-in Functions) A unique number. Nothing more, and nothing less. Think of it as a social-security number or employee id number for Python objects.
Is it the same with memory addresses in C ?
Conceptually, yes, in that they are both guaranteed to be unique in their universe during their lifetime. And in one particular implementation of Python, it actually is the memory address of the corresponding C object.
The int data type of the variable is available during lifetime and lifetime of x is not finished yet. In fact it points back to int type of x by converting back x to int.