Mutable and Immutable in Python
Table of contents
The Python data objects can be broadly categorized into two - mutable and Immutable types, in simple words changeable or modifiable and non-modifiable types.
1 Immutable types
The immutable types are those that can never change their value. In Python, the following types are immutable : Integers, Floating point Numbers, Booleans, String, Tuple,
Recall that in Python, assignment ( using an equal sign, =) assigns a reference to a value, and not the value itself. Now consider the following examples
\>>> myage = 25
\>>> yourage = myage
The above two statements will have internal impact as shown below. Both are referring to some value 25 :
As you can see above, Python has set up a reference to the value of myage, so that both variables are refering to the same object, the value 25.
Now, if you want to add a year to variable myage , you'd probably do it this way, and it appears as though it has modified the value :
But actually itt has not modified myage becouse it is immutable. Instead it has created a new object having value equal to myage + 1 and made myage refer to this new object.
thus for immutable object for any change is value, a new value object is created and the object is made to refer to the new value as explained
2 Mutable types
It, means that no new value object is created rather changes are made in the same value object , in place. For instance, if you have a list namely nums as created below :
nums = [ 1,2,3]
Internally the name nums would be referring to list [1,2,3] as shown below :
Now, if you make changes in the list nums as follows
nums = [ 1,2,3]
nums[1] = 4
Now, no new object would be created rather the same list object would be changed. See below :
Subscribe to my newsletter
Read articles from Prakash uniyal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by