-2

i tried the below code but I am not getting the reason why it is happening?

x=2
y=2
print(id(x),id(y))

in above I have got like below 140732101468592 140732101468592

but if I tried with the float type data like below

x=2.0
y=2.0
print(id(x),id(y))

I have got the output like below 2226214428496 2226204728400

why am I getting same id for integer variable with same value but not for float variable with same values?

  • Does this answer your question? [What is the id( ) function used for?](https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for) – sushanth Jun 12 '20 at 05:32
  • 1
    If this ever matters in a program you write, your program is buggy. Python makes no promises about the identities of these objects. – user2357112 Jun 12 '20 at 05:34
  • 1
    Python will share data for certain data types. There's a small range of ints that will get their references shared/ reused to save on memory. It's dependent on the interpreter implementation. – flakes Jun 12 '20 at 05:35
  • 1
    First of all your findings are based on a small example ``` x=12345 y=12345 print(id(x),id(y)) ``` if you run this you will get different IDs That is because the result of id in numeric constants is implementation-defined. In your case, Python, IIRC, the issue is that the compiler builds a few useful integer constants as singletons, (from -1 to 100 or so). The rationale is that these numbers are used so frequently that it makes no sense to dynamically allocate them each time they are needed, they are simply reused. – Kuldeep Singh Sidhu Jun 12 '20 at 05:37
  • Python [documentation](https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong) explains it quite plainly: "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. " – Aivar Paalberg Jun 12 '20 at 05:44

1 Answers1

0

The id() function returns identity of the object. As you mentioned, floats and integers are different objects in Python.

Jimmy
  • 127
  • 10