Immutable Data Types in Python: What They Are and How They Work
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.
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}")
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.