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:
# Example 1: Getting the id of an integer
num = 42
print(id(num))
Output:
140705772893184
In this example, the id()
function returns a unique identifier representing the memory address of the integer 42
.
Object Identity:
# Example 2: Comparing the ids of two objects
a = [1, 2, 3]
b = [1, 2, 3]
print(id(a))
print(id(b))
print(a is b)
Output:
139940860835840
139940860837312
False
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:
# Example 3: Using id() for identity comparison
x = "Hello"
y = "Hello"
print(id(x))
print(id(y))
print(x is y)
Output:
140705528575600
140705528575600
True
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:
# Example 4: Modifying an object and observing id changes
z = [1, 2, 3]
print(id(z))
z.append(4)
print(id(z))
Output:
139940860579840
139940860579840
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:
# Example 5: Demonstrating the difference between identity and equality
p = [1, 2, 3]
q = p
print(id(p))
print(id(q))
print(p == q)
print(p is q)
Output:
139940860833728
139940860833728
True
True
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.