Junior — Middle
How do you distinguish between mutable and immutable data types in Python?
sobes.tech AI
Answer from AI
In Python, mutable data types are objects whose contents can be changed after creation, while immutable data types are objects that cannot be changed after creation.
Examples of immutable types: int, float, bool, str, tuple, frozenset.
Examples of mutable types: list, dict, set, user-defined objects with mutable state.
To distinguish, you can check whether an object changes when you try to modify its contents:
# Mutable list
lst = [1, 2, 3]
lst[0] = 10 # works
# Immutable tuple
t = (1, 2, 3)
t[0] = 10 # will raise a TypeError
Mutable objects are useful when you need to change data without creating new objects, while immutable objects are used to protect data from modifications and as keys in dictionaries.