Python Built-in Classes :
Mutable vs Immutable in Python :
Let’s see with an example:
List is an example of mutable classes.
lst=(‘A’, ‘B’, ‘C’)
print(lst) — — — — (‘A’, ‘B’, ‘C’)
lst.append(‘D’) #append() adds an element to the end of a list
print(lst) — — — — (‘A’, ‘B’, ‘C’, ‘D’)
The append() adds the element ‘D’ to the original list. That means ,in the case of mutable classes, the changes are done in the original memory.
String is an example of immutable classes.
str= “hello”
print(str+ ‘5’) — — — hello5
print(str) — — — hello
The above example explains that the changes are not done in the original memory. It only stores the value which is given during the initialization.
Creating alias(x) will have the same memory location as that of the original class(lst).The changes made in the alias will reflect in the original class.
Alias(X) will have the same value as that of original(Y) but different memory location and this is why the changes done in the alias are not reflected in the original class.