Python’s id()
function is a built-in method that returns the identity of an object, a unique identifier representing the object’s memory address. Understanding how id()
works is crucial for grasping concepts related to memory management and object identity in Python. In this comprehensive guide, we’ll explore the intricacies of id()
with detailed examples to help you comprehend its functionality thoroughly.
Basic Usage:
Output:
In this example, the id()
function returns a unique identifier representing the memory address of the integer 42
.
Object Identity:
Output:
Each object in Python has a unique identity, even if they have the same value. In this example, a
and b
refer to different objects, as evidenced by their distinct ids.
Identity Comparison:
Output:
For immutable objects like strings, Python optimizes memory usage by reusing objects with the same value. Thus, x
and y
have the same id and are considered identical.
Modifying Objects:
Output:
The id of an object remains the same as long as its identity is preserved. Even after modifying the list z
, its id remains unchanged.
Understanding Identity and Equality:
Output:
In Python, ==
checks for equality (i.e., whether the values are the same), while is
checks for identity (i.e., whether the objects refer to the same memory location). Here, p
and q
have the same id because they refer to the same list object.