|

Mutable vs. Immutable Objects in Python: Why It Matters

3D comparison of a flexible clay object (mutable) versus a solid stone object (immutable), representing Python object types.

In Python, everything is an object. One of the most common concepts you’ll encounter is Mutable vs Immutable Python. But some objects can change (Mutable), and some cannot (Immutable).

  • Immutable (Cannot Change): Integers, Floats, Strings, Tuples.
  • Mutable (Can Change): Lists, Dictionaries, Sets.

The “Gotcha” Moment

If you assign a mutable object to a new variable, you don’t get a copy; you get a reference to the same object.

# List A
list_a = [1, 2, 3]

# List B is now THE SAME object as List A
list_b = list_a

# We change List B
list_b.append(4)

# SURPRISE! List A also changed!
print(list_a) 
# Output: [1, 2, 3, 4]

This happens because they are both pointing to the same list in memory.

How to Fix It (Making a Real Copy)

If you want a truly separate copy, you must ask for it explicitly.

# The .copy() method creates a NEW list with the same data
list_b = list_a.copy()

list_b.append(4)
print(list_a) 
# Output: [1, 2, 3] (Safe!)

Understanding this difference is critical when passing lists into functions!

Similar Posts

Leave a Reply