Junior — Middle
Explain what immutability means in data types and its advantages.
sobes.tech AI
Answer from AI
Immutability is a property of an object or data type whereby its state cannot be changed after creation. In Python, examples of immutable types include strings (str), tuples (tuple), and numbers (int, float).
Advantages of immutability:
- Thread safety: objects do not change, so there are no synchronization issues.
- Simplifies code understanding: the object's state is fixed, reducing the likelihood of errors.
- Used as dictionary keys and set elements: only immutable objects can be hashed.
Example:
s = "hello"
# s[0] = 'H' # Error, strings are immutable
t = (1, 2, 3)
# t[0] = 10 # Error, tuples are immutable
# To modify, create a new object
s_new = "H" + s[1:]
Thus, immutability helps create more reliable and predictable code.