Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python id() Function

Python id() Function

Python3 Built-in Functions Python3 built-in function


id() is a built-in Python function that gets an object's unique identifier.

In Python, every object has a unique integer identifier that is unique and constant for the lifetime of the object.id() It returns this identifier, which usually corresponds to the object's memory address.

Word meaning: id Is identifieris short for (identifier).


Basic syntax and parameters

Syntax format


id(object)

Parameter Description

- Type: any object - Description: the object whose identifier is wanted.

Function description


Example

Example 1: basic usage

Example

View the id of an integer

a

=

10

print

(

id

(

a

)

)

 

Output: an integer, such as 4302400000

View the id of a string

s

=

"hello"

print

(

id

(

s

)

)

 

Output: an integer

View the id of a list

lst

=

[

1

,

2

,

3

]

print

(

id

(

lst

)

)

 

Output: an integer

Expected output:

Returns the object's unique identifier (an integer).

Code analysis:

  1. Every object has a unique id.
  2. Different objects usually have different ids.

Example 2: verifying object identity

Example

Multiple references to the same object

a

=

[

1

,

2

,

3

]

b

=

a

print

(

id

(

a

)

==

id

(

b

)

)

 

Output: True (a and b point to the same object)

Copy the object

a

=

[

1

,

2

,

3

]

b

=

a.

copy

(

)

print

(

id

(

a

)

==

id

(

b

)

)

 

Output: False (a and b are different objects)

Integer caching (small integers)

a

=

256

b

=

256

print

(

id

(

a

)

==

id

(

b

)

)

 

Output: True (small integers are cached)

a

=

257

b

=

257

print

(

id

(

a

)

==

id

(

b

)

)

 

Output: False (large integers are not cached)

Expected output:

True
False
True
False

Code analysis:

Example 3: practical applications

Example

Check whether they are the same object

def

check_same_object

(

a

,

b

)

:

   

return

id

(

a

)

==

id

(

b

)

Testing

list1

=

[

1

,

2

,

3

]

list2

=

list1

list3

=

[

1

,

2

,

3

]

print

(

check_same_object

(

list1

,

list2

)

)

 

Output: True

print

(

check_same_object

(

list1

,

list3

)

)

 

Output: False

As a dictionary key (though uncommon)

d

=

{

}

obj

=

object

(

)

d

[

obj

]

=

"value"

print

(

d

[

obj

]

)

 

Output: value

View objects while debugging

class

Person:

   

pass

p

=

Person

(

)

print

(

f

"Object id: {id(p)}"

)

print

(

f

"Class id: {id(Person)}"

)

Expected output:

True
False
value
对象 id: ...
类 id: ...

id() Mainly used for debugging, checking object identity, understanding Python memory management, and so on.


Python3 Built-in Functions Python3 built-in function