CS101:2.1.3.2:Python Confused over Mutable Vs. Immutable


#1

If the data of an object can be changed after it is created, the object is said to be mutable.


I must not understand that statement because in my head, every class I've ever created in any language has been mutable, I have always been able to use a method to change a data member value. Yet, in Python, only the list, dictionary, and file primitive types are mutable? To me that means no data member could ever be changed, but I know that is obviously not right, which leads me to realize that I don't understand what mutable and immutable really mean. I can't find anything else on the web that has helped me.


Can anyone elaborate?


#2

Hello there,
I am still a learner myself, so do not take, what I’m about to say for gospel.
The way I understand this mutable and immutable topic has something to to do with the question if the actual memory location is changed or not. I am not too sure how Python works in detail but there is a great example in Java that illustrates this to some degree. If you look at the String class, Strings are immutable, which means, that once a string object has been created, this object (the data in memory) can not be changed. What can be changed is the reference to the object (reference variables vs value type variables). For example, if you create a new String object (String exampleStringA = “This is a sample sting”) what actually happens in the background is that a new object gets created that holds the data “This is a sample string” and then a reference to that object is put into exampleStringA. The data in the object can not be changed. You can make exampleStringA pointing to another object but that is about it. Therefore, there are some immutable classes, and I am sure there are some more out there other than the Java String class.
Anyway, I hope that kind of answers your question.
Oh yes, and if someone else is reading this and realizes that I am utterly wrong about what I just said, please please please, let me know. :grinning:


#3

Everything in Python is an object . You have to understand that Python represents all its data as objects. An object’s mutability is determined by its type. Some of these objects like lists and dictionaries are mutable , meaning you can change their content without changing their identity. Other objects like integers, floats, strings and tuples are objects that can not be changed.

Strings are Immutable

Strings are immutable in Python, which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original.