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?
It is the address of the object in memory, exactly as the doc says. However, it has metadata attached to it, properties of the object and location in the memory is needed to store the metadata. So, when you create your variable called list, you also create metadata for the list and its elements.
So, unless you an absolute guru in the language you can't determine the id of the next element of your list based on the previous element, because you don't know what the language allocates along with the elements.
I have an idea to use value of
id()
in logging.It's cheap to get and it's quite short.
In my case I use tornado and
id()
would like to have an anchor to group messages scattered and mixed over file by web socket.If you're using python 3.4.1 then you get a different answer to your question.
returns:
The integers
-5
to256
have a constant id, and on finding it multiple times its id does not change, unlike all other numbers before or after it that have different id's every time you find it. The numbers from-5
to256
have id's in increasing order and differ by16
.The number returned by
id()
function is a unique id given to each item stored in memory and it is analogy wise the same as the memory location in C.Your post asks several questions:
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.
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.
Because a list is not an array, and a list element is a reference, not an object.
Hardly ever.
id()
(or its equivalent) is used in theis
operator.