What is the id( ) function used for?

前端 未结 13 991
傲寒
傲寒 2020-11-22 10:51

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

13条回答
  •  孤街浪徒
    2020-11-22 11:06

    If you're using python 3.4.1 then you get a different answer to your question.

    list = [1,2,3]
    id(list[0])
    id(list[1])
    id(list[2])
    

    returns:

    1705950792   
    1705950808  # increased by 16   
    1705950824  # increased by 16
    

    The integers -5 to 256 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 to 256 have id's in increasing order and differ by 16.

    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.

提交回复
热议问题