Python id() 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
- Parameter object:
- Type: any object
- Description: the object whose identifier is wanted.
Function description
- Return Value: returns an integer representing the object's unique identifier.
- Feature: the id remains constant throughout the object's lifetime.
Example
Example 1: basic usage
Example
View the id of an integer
a
=
10
(
id
(
a
)
)
Output: an integer, such as 4302400000
View the id of a string
s
=
"hello"
(
id
(
s
)
)
Output: an integer
View the id of a list
lst
=
[
1
,
2
,
3
]
(
id
(
lst
)
)
Output: an integer
Expected output:
Returns the object's unique identifier (an integer).
Code analysis:
- Every object has a unique id.
- Different objects usually have different ids.
Example 2: verifying object identity
Example
Multiple references to the same object
a
=
[
1
,
2
,
3
]
b
=
a
(
id
(
a
)
==
id
(
b
)
)
Output: True (a and b point to the same object)
Copy the object
a
=
[
1
,
2
,
3
]
b
=
a.
copy
(
)
(
id
(
a
)
==
id
(
b
)
)
Output: False (a and b are different objects)
Integer caching (small integers)
a
=
256
b
=
256
(
id
(
a
)
==
id
(
b
)
)
Output: True (small integers are cached)
a
=
257
b
=
257
(
id
(
a
)
==
id
(
b
)
)
Output: False (large integers are not cached)
Expected output:
True
False
True
False
Code analysis:
- Use
==Comparing ids can determine whether they are the same object. - Python caches small integers (-5 to 256), so variables with the same value may share an id.
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
]
(
check_same_object
(
list1
,
list2
)
)
Output: True
(
check_same_object
(
list1
,
list3
)
)
Output: False
As a dictionary key (though uncommon)
d
=
{
}
obj
=
object
(
)
d
[
obj
]
=
"value"
(
d
[
obj
]
)
Output: value
View objects while debugging
class
Person:
pass
p
=
Person
(
)
(
f
"Object id: {id(p)}"
)
(
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 function