1

Program:

a = 5
b = 5
print(a == b)
print(id(a) == id(b))

Output:

True
True

I understand the first line of the output should be True, but why is the second line also True? Doesn't the operator id() spit out the memory location? Does the constant 5 get a specific memory location when it is used in the program?

Also, if that is the case, how can we return the memory location of the variables a and b?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • 1
    It's due to Python's [cashing of small integers](https://www.codementor.io/@arpitbhayani/python-caches-integers-16jih595jk). Try with `-6` or `257`. – PM 77-1 Jan 06 '23 at 19:06
  • This is [clearly documentated](https://docs.python.org/3/library/functions.html#id): "Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same `id()` value." – juanpa.arrivillaga Jan 06 '23 at 19:32
  • "Doesn't the operator id() spit out the memory location?". As the docs say, in CPython, `id` **happens** to return the address of the Python object (to be precise, the address of the PyObject header). But that is an implementation detail. All you should ever think is that it is *an integer which is guaranteed to be unique and constant for this object during its lifetime.*. So yes, `a` and `b` are referring to the *same object*. – juanpa.arrivillaga Jan 06 '23 at 19:34

0 Answers0