Page 70 - IPP-11
P. 70
Python Programming
3 Fundamentals
(Additions)
3.13 MUTABLE AND IMMUTABLE TYPES
In certain situations, we may require changing or updating the values of certain variables used
in a program. However, for certain data types, Python does not allow us to change the values
once a variable of that type has been created and assigned values.
Variables whose values can be changed after they are created and assigned values are called
mutable variables.
Variables whose values cannot be changed after they are created and assigned values are called
immutable variables. When an attempt is made to update the value of an immutable variable,
the old variable is destroyed and a new variable is created by the same name in memory.
Python data types can be classified into mutable and immutable as under:
Examples of mutable objects: list, dictionary, set, etc.
Examples of immutable objects: int, float, complex, bool, string, tuple, etc.
For example, int is an immutable type which, once created, cannot be modified.
Consider a variable ‘x’ of integer type:
>>> x = 5
Now, we create another variable ‘y’ which is a copy of variable ‘x’.
>>> y = x
The above statement will make y refer to value 5 of x. We are creating an object of type int.
Identifiers x and y point to the same object.
x = 5
This statement will create a value 5 referenced by x.
x
5
y
Now, we give another statement as:
>>> x = x + y