MUTABLE AND IMMUTABLE TYPES IN PYTHON
Python represents its data as objects. Some of these objects (such as lists and dictionaries) are mutable, which means you can change their content without changing their identity. Objects such as integers, floats, strings, and tuples are objects that cannot be changed.
There is a difference between changing the value versus assigning a new value to an object; you cannot change a string, but you can assign it a different value. This detail can be verified by checking the id value of an object, as shown in Listing 3.12.
Listing 3.12: Mutability.py
s = "abc"
print('id #1:', id(s))
print('first char:', s[0])
try:
s[0] = "o"
except:
print('Cannot perform reassignment')
s = "xyz"
print('id #2:',id(s))
s += "uvw"
print('id #3:',id(s))
The output of Listing 3.12 is here:
id #1: 4297972672
first char: a
Cannot perform reassignment...