This content originally appeared on DEV Community and was authored by Arnold Chris
Why are data types either mutable or immutable?
Lets look at python as an example,
Data types in python are basically objects or classes, int is a class, floats, lists etc.
Therefore, writing x=6
creates a new integer object with a value of 6 and points a reference called x at this object.
Now we need to look into classes, classes basically group data and functions together, there functions are called Methods and they are of two types: accessor and mutator methods.
Accessor methods access the current state of an object but doesn't change the object itself e.g
x = "hello"
y = x.upper()
Here the method upper is called on the object that x refers to, the upper accessor then returns a new object, a str object that is an upper-cased version of the original string. (feel free to re-read) , basically it returns a new object based on the original now only it is uppercased.
Mutator methods on the other hand change the values in the existing objects and a good example is the list type(class).
newList = [1,2,3]
newList.reverse()
This method will mutate the existing object, a mutator method can't be undone.
Data types that lack these mutator methods are said to be immutable and hence only contain accessor methods, one that lack are mutable.
Hope this helped, stay curious :)
This content originally appeared on DEV Community and was authored by Arnold Chris
Arnold Chris | Sciencx (2024-08-11T15:46:15+00:00) What do we REALLY mean by immutable data types?. Retrieved from https://www.scien.cx/2024/08/11/what-do-we-really-mean-by-immutable-data-types/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.