Understanding Python Object IDs (Short Notes)
Example Code:
a = 3
print(id(a))
a = 4
print(id(a))
print(a is a)
Key Concepts:
1. Object ID:
2. id() function returns the unique identity (memory address-like) of an object.
3. Assignment:
4. a = 3 assigns a to an integer object 3 .
5. a = 4 reassigns a to another integer object 4 . 3 and 4 are different immutable objects.
6. is operator:
7. a is a will always return True because any object is identical to itself.
8. Integer Interning:
9. Small integers (typically -5 to 256) are cached (interned) in Python.
10. Multiple variables assigned the same small integer will point to the same object.
Example:
a = 5
b = 5
print(a is b) # True because 5 is interned
x = 1000
1
y = 1000
print(x is y) # May be False because large integers may not be interned
Summary Table:
Action Result
a = 3 a points to object 3
a = 4 a points to object 4
a is a True
a is b (small integers) True (due to interning)
a is b (large integers) May be False
Note:
• Python integers are immutable.
• Reassigning a variable does not change the object; it changes what the variable points to.