For mutable objects, such as a list, to operate on a list, the contents within the list will change, for example.
>>> l = ['f', 'e', 'd'] >>> l.sort() >>> ; ['d', 'e', 'f']
What about immutable objects, like string.
>>> str = 'hello' >>> str.replace('h', 'F') 'Fello' >>> str 'hello'
Even though the string has a replace() method and does change to ‘Fello’, but the variable str value is still ‘hello’. How to understand?
Let’s change the code to below.
>>> str = 'hello' >>> str1 = str.replace('h', 'F') >>> str1 'Fello' >>> str 'hello'
Keep in mind that str is a variable and ‘hello’ is a string object. The contents of object str are ‘hello’ means that str itself is a variable, and the content of the object it points to is ‘hello’.
When we call str.replace(‘h’, ‘F’), we actually call the method replace on the string object ‘hello ‘, but it does not change the content of the string ‘hello’. Instead, the replace method creates a new string ‘Fello’ and returns it.
If we point the variable str1 to the new string, it’s easy to understand that variable str still points to the original string ‘hello’, but variable str1 points to the new string ‘Fello’.
So, for immutable objects, calling any method of the object itself does not change the content of the object itself. Instead, these methods create new objects and return them, so that the immutable objects themselves are always immutable.