Mutable and Immutable objects in Python. Let's discuss it!
Mutable Object: An object that can be modified or changed after being created is a mutable object. E.g. Variable with data type as a list, set, dictionary etc. The below code is a simple example of how mutable objects work.
Let's say 'v' is a list-type variable saving multiple integers.
v = [1,2,3,4,5]
v[-2] = 10 #This line of code will replace element '4' by '10' in variable 'v'
Now the v variable has element [1,2,3,10,5]
Immutable Object: It is the vice versa of a mutable object. Here, we cannot change or modify any element after creation. E.g. Variable with data type as a tuple or string.
Below, I have written a simple code which makes it seem like the string variables are mutable but they are not. Follow along!
Let's say 's' is a string-type variable saving word 'Siddharth'.
s = 'Siddharth'
s.replace('S', 'A')
The output of the above code is 'Aiddharth'. However, this value is saved locally and it does not replace the value saved by variable 's'. Variable 's' will still show the value as 'Siddharth'. In order to save the output 'Aiddharth', we need to assign it to a new variable 'New_v'. Now, 's' variable has value 'Siddharth' and 'New_v' variable has value 'Aiddharth'.
Hope, the above explanation will help you to understand the difference between the two.