Understanding Python's id(): Memory Addresses and Object Identity

Understanding Python's id(): Memory Addresses and Object Identity ๐Ÿง 

The id() function in Python reveals an object's memory address (or unique identity). It's especially useful when comparing object references, debugging, or understanding how Python stores data in memory.

Python memory address icon

✅ Immutable objects: shared memory

# Immutable integers: same value = same object
a = 100
b = 100
print(id(a), id(b))       # same ID
print(a is b)             # True
print(a == b)             # True

✅ Mutable objects: separate memory

# Mutable lists: same content ≠ same object
x = [1, 2, 3]
y = [1, 2, 3]
print(id(x), id(y))       # different IDs
print(x is y)             # False
print(x == y)             # True

✅ Reference assignment: same ID

# Variable reference copy
z = x
print(id(x), id(z))       # same ID
print(x is z)             # True

✅ Tracking identity inside functions

# Tracking memory with id() inside a function
def trace_obj(obj):
    print(f"ID: {id(obj)}, VALUE: {obj}")

trace_obj(x)
trace_obj(y)

Using id() helps you distinguish between "same value" and "same object". In Python, knowing whether you're dealing with a copy or a reference can save you from unexpected behavior.

Value is not identity. Use id() to see beneath the surface and trace your objects like a pro. ๐Ÿš€

Icons by Flaticon

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“