Python Forum
What is the meaning of mutable data type? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: What is the meaning of mutable data type? (/thread-25976.html)



What is the meaning of mutable data type? - qliu - Apr-17-2020

Hello everyone, I have one simple question which I can not figure out by myself. Would you please share your opinion and help me walking through this?
The question is: what is the meaning of making the difference between mutable and immutable data type in python? Could anyone please tell me what kind of benefits the mutable data type could offer comparing to the immutable data type, maybe give me an example?
Thanks.


RE: What is the meaning of mutable data type? - Yoriz - Apr-17-2020

mutable
Mutable objects can change their value but keep their id().

immutable
An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.


RE: What is the meaning of mutable data type? - pframe - Apr-17-2020

Mutable = can change

Immutable = can't change.

Eg =

A list is mutable as I can add/remove elements.

A tuple is immutable as once I declare it, I can't add/remove any elements.


RE: What is the meaning of mutable data type? - deanhystad - Apr-17-2020

The first time I ran across immutable strings I found it very confusing, but that was coming from a world were there was no garbage collection unless I did it myself. In C you create/protect/cherish your data structures because they are the foundation of your program. In Python they are tossed away like a used tissue.

But I have to say there are some nice things about immutable strings. I don't have to worry about a string changing value in python. In C, if I kept a string I usually made a copy to protect against the string changing outside the scope of my module. Python does that automatically, and only if I need a copy. If the string I am passed never changes it can be used all over the place and still be the only string. No copies unless needed and then the copies are made automatically. How cool is that!

To a lesser extent I like tuples for the same reason. If I put something in a tuple I don't have to worry about it changing. If I want something that acts more like a C array (a shared resource that can be modified and all users have access to the same modified value) I just use a list (or a python array).