The id()
function returns the unique memory address of an object. It’s useful for checking object identity, debugging, and understanding how Python handles variables in memory.
Example
x = 42
print(id(x))
# Output: (Unique memory address)
Each variable has a unique identifier based on its memory location.
Syntax
id(object)
- object → The variable or object to check.
- Returns → A unique integer representing the memory address.
1. Checking If Two Variables Point to the Same Object
a = 100
b = a
print(id(a) == id(b))
# Output: True
Since b
references the same object as a
, both have the same id
.
2. Comparing Mutable and Immutable Objects
Mutable objects change memory location when modified.
list1 = [1, 2, 3]
list2 = list1 # Same reference
print(id(list1) == id(list2)) # Output: True
list1.append(4) # Modify list1
print(id(list1) == id(list2)) # Output: True (Same memory location)
Since lists are mutable, changes affect both list1
and list2
.
Immutable objects get a new memory location when modified
x = 10
y = x # Same reference
print(id(x) == id(y)) # Output: True
x += 1 # Creates a new object
print(id(x) == id(y)) # Output: False
Numbers, strings, and tuples are immutable, so modifying them creates new objects.
3. Checking Object Identity in Functions
Use id()
to see if a function modifies an object in-place.
def modify(lst):
print("Before:", id(lst))
lst.append(100)
print("After:", id(lst))
nums = [1, 2, 3]
modify(nums)
# Output:
# Before: (Memory address)
# After: (Same memory address)
This proves that lists are modified in-place.
Key Notes
- ✔ Returns a unique identifier (memory address) for an object.
- ✔ Shows if two variables point to the same object.
- ✔ Immutable objects get new memory addresses when modified.
- ✔ Useful for debugging and understanding variable behavior.
By using id()
, you can check how Python manages memory, making it easier to debug and optimize your code. 🚀