0
0
PythonConceptBeginner · 3 min read

Immutable Data Types in Python: What They Are and How They Work

In Python, immutable data types are types whose values cannot be changed after they are created. Examples include int, float, str, and tuple. Once created, you cannot modify their content, only create new objects.
⚙️

How It Works

Imagine you have a printed photo. Once printed, you cannot change the picture on it; you can only print a new photo if you want a different image. Immutable data types in Python work similarly. When you create an immutable object, its value is fixed and cannot be altered.

This means if you try to change an immutable object, Python will create a new object instead of modifying the original one. This behavior helps keep data safe from accidental changes and can improve program reliability.

💻

Example

This example shows how changing an immutable type like a string creates a new object instead of modifying the original.

python
original = "hello"
print(f"Original id: {id(original)}")

modified = original.upper()
print(f"Modified id: {id(modified)}")

print(f"Original value: {original}")
print(f"Modified value: {modified}")
Output
Original id: 140430123456784 Modified id: 140430123457024 Original value: hello Modified value: HELLO
🎯

When to Use

Use immutable data types when you want to ensure data does not change unexpectedly. For example, strings are immutable because changing text often means creating new text rather than editing existing text.

Immutable types are great for keys in dictionaries or elements in sets because their fixed value guarantees consistent behavior. They also help avoid bugs caused by accidental data changes in programs.

Key Points

  • Immutable types cannot be changed after creation.
  • Common immutable types: int, float, str, tuple, frozenset.
  • Modifying an immutable object creates a new object.
  • Immutable objects are safe to use as dictionary keys or set elements.

Key Takeaways

Immutable data types cannot be changed once created, ensuring data safety.
Examples include int, float, str, tuple, and frozenset.
Changing an immutable object creates a new object instead of modifying the original.
Use immutable types when you need fixed, reliable data like dictionary keys.
Understanding immutability helps prevent bugs from accidental data changes.