Junior — Middle
Explain the concept and features of immutable data types in Python
sobes.tech AI
Answer from AI
In Python, immutable data types are objects whose state cannot be changed after creation. Examples of such types include strings (str), tuples (tuple), numbers (int, float), boolean values (bool), and some others.
Features of immutable types:
- Safety and predictability: since the object does not change, it can be safely used as a dictionary key or a set element.
- Memory optimization: interning strings and caching numbers is possible due to immutability.
- Behavior upon modification: attempting to modify an object creates a new object, and the reference points to the new object.
Example:
s = "hello"
s = s + " world" # a new string object is created, and s now references it
Here, the original string "hello" remains unchanged, and a new string "hello world" is created.