Junior — Middle
Can you explain what are immutable data structures and their purpose?
sobes.tech AI
Answer from AI
Data structures that cannot be changed after creation are called immutable. In Python, these include, for example, tuples (tuple), strings (str), numbers (int, float), and frozenset.
Immutability means that once an object is created, its contents cannot be altered — any operations that seem to modify the object actually create a new object.
This is useful for ensuring data security, preventing side effects, and simplifying work with multithreading.
Example with a tuple:
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error: cannot change an element
new_tuple = my_tuple + (4,) # Creates a new tuple
print(new_tuple) # (1, 2, 3, 4)