'Is id() function buggy? [duplicate]

Take a look at this:

screenshot showing usage of id() function

According to python documentation, every object is given a different reference id every session... but when I run this code, as you can see id(1001) is equal to id(1002) until I run the expression id(1001) == id(1002) which is when id of 1001 changes... can anyone tell me how the heck does this work? I did check some other questions that seemed similar but couldn't find an answer.



Solution 1:[1]

This is because of pythons reference counting!

Whenever you use any integer, string or whatever, Python creates a new object in memory for you. While it's reference count is not zero the id will be unique for that object.

When you type:

>>> id(1000)
140497411829680

Python creates 1000, returns its id and then removes the object from memory, since it is not referenced anywhere else. This is because you could otherwise fill your whole memory with only id(1000), while it is actually the same object.

this is also why:

>>> id(1000)
140697307073456
>>> id(1001)
140697307073456

returns the same id. You can try to set a variable with your integer and see the difference:

>>> a = 1000
>>> id(a)
140697307073456
>>> b = 1001
>>> id(b)
140697306008468

Here, python keeps the object and id in memory, since it's reference count is not zero!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1