[Python] What is `id()` function used for in Python?

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página