This guide explains id() Function: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
id(value) returns an integer that identifies an object during its lifetime. In CPython this often relates to an address, but the Python language does not promise a particular ID calculation or stable numeric value across runs.
When You Would Use This
Object identity helps explain the difference between two names referring to one list and two independent lists.
Step-by-Step Example
first_list = [2, 4]
alias_list = first_list
new_list = [2, 4]
print(first_list is alias_list)
print(first_list is new_list)
print(id(first_list) == id(alias_list))
How the Example Works
An alias shares the same object, so the first and last checks return True. Creating a separate list with the same contents makes the second check False. The actual numeric identifier is deliberately not printed.
Example Output
True
False
True
Try It Yourself
Assign one dictionary to two names; mutate it through one name and inspect the other.
Common Beginner Mistakes
- Expecting the actual ID number to be predictable or constant across launches.
- Using
id()to compare values instead of using==. - Assuming small integer or string interning behavior is a reliable identity rule.
Key Takeaways
id(value)returns an integer that identifies an object during its lifetime.- An alias shares the same object, so the first and last checks return
True. - Avoid this mistake: Expecting the actual ID number to be predictable or constant across launches.