Andromeda
Note

Immutable Objects (Python)

Definition

Immutable Objects in Python are objects whose state cannot be changed after creation (e.g., tuples, strings, integers).

Why It Matters

They are inherently thread-safe and hashable, making them reliable keys in dictionaries and preventing accidental data mutation.

Core Concepts

# Strings are immutable
s = "Hello"
print(id(s))
s += " World"
print(id(s))  # Different ID (New object created)

# Tuples are immutable
t = (1, 2)
# t[0] = 3  # This would trigger a TypeError
  • 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.

Connected Concepts