Junior — Middle
Explain the concept of immutable data types and their features.
sobes.tech AI
Answer from AI
Immutable data types are objects whose state cannot be changed after creation. In Python, such types include, for example, strings (str), tuples (tuple), numbers (int, float).
Features of immutable types:
- After an object is created, its contents do not change. Any operation that appears to modify the object actually creates a new object.
- Because of this, immutable objects are safe to use as keys in dictionaries and elements in sets.
- Immutability makes debugging easier and prevents errors related to unintentional data modification.
Example:
s = "hello"
s2 = s.replace('h', 'j') # a new string is created
print(s) # hello
print(s2) # jello
Here, the original string s is not changed, and replace returns a new string.