0

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
None
  • 3
  • 3
  • The value of `x` before and after the conversion is the same number 10. That's why it has the same id. – DYZ Mar 16 '17 at 07:44
  • 1
    @DYZ that is not generally true for objects, though, and only happens to be true on CPython for ints between -5 and 256 – juanpa.arrivillaga Mar 16 '17 at 08:00
  • @juanpa.arrivillaga I did not generalize to _objects_, I only made a claim for the number 10. I agree with the rest of your remark. – DYZ Mar 16 '17 at 08:01
  • But this doesn't even generalize to all `int` objects, for example, it doesn't work for `a = 1000; b = 1000` I'm just saying your statement is misleading without a little more information. – juanpa.arrivillaga Mar 16 '17 at 08:02

4 Answers4

3

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.

See this question and it's great answer for more detail.

Community
  • 1
  • 1
Pit
  • 3,606
  • 1
  • 25
  • 34
1

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.

mebusy
  • 21
  • 4
0
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.

what-does-id-function-used-for

Community
  • 1
  • 1
Ajay Singh
  • 1,251
  • 14
  • 17
-2

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.

Mehrdad
  • 2,054
  • 3
  • 20
  • 34