Page 71 - IPP-11
P. 71
The above statement shall result in adding up the value of x and y and assigning to x.
Thus, x gets rebuilt to 10.
x 10
y 5
The object in which x was tagged is changed. Object x = 5 was never modified. An immutable
object doesn’t allow modification after creation. Another example of immutable object
is a string.
>>> str = "strings immutable"
>>> str[0] = 'p'
>>> print(str)
This statement shall result in TypeError on execution.
TypeError: 'str' object does not support item assignment.
This is because of the fact that strings are immutable. On the contrary, a mutable type object
such as a list can be modified even after creation, whenever and wherever required.
new_list = [10, 20, 30]
print(new_list)
Output:
[10, 20,30]
Suppose we need to change the first element in the above list as:
Supplement – Informatics Practices with Python–XI
new_list = [10, 20, 30]
new_list[0] =100
print(new_list) will make the necessary updation in the list new_list and shall display the
output as:
[100, 20,30]
This operation is successful since lists are mutable.
Python handles mutable and immutable objects differently. Immutable objects are quicker to
access than mutable objects. Also, immutable objects are fundamentally expensive to “change”
because doing so involves creating a copy. Changing mutable objects is cheap.
3.14 TYPE CONVERSION (TYPE CASTING)
As and when required, we can change the data type of a variable in Python from one type to
another. Such data type conversion can happen in two ways:
• either explicitly (forced) when the programmer specifies for the interpreter to convert a
data type into another type; or
• implicitly, when the interpreter understands such a need by itself and does the type
conversion automatically.
3.2