I understand that immutable objects cannot be changed in place. A new object is created and reassigned to the same variable name. In this way, we can maintain the association to the variable. Internally, the variable points to a different object.
>>> string = 'object'
>>> old_id = id(string)
>>> old_id
4452633584
>>> string = 'new' + string
>>> new_id = id(string)
>>> new_id
4501338544
>>> old_id == new_id
False
In the above example, does Python create a mutable clone of string
to concatenate to 'new'
, and then, make this new object immutable before reassignment to string
?
I don't understand how objects, that cannot be changed in place, can also be operated on.
Doesn't Python need a changeable thing to change in order to produce a new thing? If I want to hammer a nail into a piece of wood, but that wood is unchangeable, how do I end up with a hammered piece of wood?