|

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!


Key Takeaways

  • In Python, objects can be Mutable (changeable) or Immutable (unchangeable).
  • Immutable objects include Integers, Floats, Strings, and Tuples.
  • Mutable objects include Lists, Dictionaries, and Sets.
  • Assigning a mutable object to a new variable creates a reference to the same object, not a copy.
  • To create a separate copy, you must explicitly request it, which is crucial when passing lists to functions.

Similar Posts

Leave a Reply