Question
Asked By – Thanakron Tandavas
I read the Python 2 docs and noticed the id()
function:
Return the “identity” of an object. This is an integer (or long 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.
CPython implementation detail: This is the address of the object in memory.
So, I experimented by using id()
with a list:
>>> list = [1,2,3]
>>> id(list[0])
31186196
>>> id(list[1])
31907092 // increased by 896
>>> id(list[2])
31907080 // decreased by 12
What is the integer returned from the function? Is it synonymous to memory addresses in C? If so, why doesn’t the integer correspond to the size of the data type?
When is id()
used in practice?
Now we will see solution for issue: What is the id( ) function used for?
Answer
Your post asks several questions:
What is the number returned from the function?
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.
If yes, why doesn’t the number increase instantly by the size of the data type (I assume that it would be int)?
Because a list is not an array, and a list element is a reference, not an object.
When do we really use
id( )
function?
Hardly ever. You can test if two references are the same by comparing their ids, but the is
operator has always been the recommended way of doing that. id( )
is only really useful in debugging situations.
This question is answered By – Robᵩ
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0