Andromeda
Note

Mutable Objects (Python)

Definition

Mutable Objects in Python are objects whose internal state can be modified in-place after creation (e.g., lists, dictionaries, sets).

Why It Matters

They are highly memory-efficient for dynamic updates, but can introduce bugs through unintended side-effects and shared references.

Core Concepts

  • Mutable Types: Lists, Dictionaries, Sets. You can change their contents without creating a new object in memory.
  • Immutable Types: Strings, Tuples, Integers, Floats. Any “modification” (like string concatenation) actually creates a brand new object at a new memory address.
  • Stability: Immutable objects are inherently “safer” because they cannot be changed by side effects. This makes them suitable as dictionary keys.
  • Sequence Context: Lists (mutable) and Tuples (immutable) are both sequence types, sharing indexing and slicing syntax, but differing in this core property.
# Mutable object (list)
my_list = [1, 2, 3]
my_list.append(4)  # Modified in-place

# Immutable object (string)
my_string = "Hello"
# my_string[0] = "h"  # This would raise a TypeError
new_string = my_string.lower()  # Creates a new object

Connected Concepts