A Python object is either mutable, meaning capable of being changed after it is created or immutable, unchangeable after creation. Since Python is an Object Oriented Programming language, It is important to understand which object types can truly be changed or are just faux changed. To help understand what an object is and if it truly can change, I will use the Python builtin functions type() and id() as well as the comparison operators ‘is’ and ‘==’.
Built-in type() , when called on a variable, returns the object type the variable points too. Built-in id(), when called on a variable, returns an integer which is guaranteed to be unique and constant for this object during its lifetime. The operator ‘is’ is a boolean evaluator that returns True if object a and b have the same id. The ‘==’ operator returns True if object a and b are the same thing but not necessarily the same id number.
The following are some mutable Python objects — list, dict, set, bytearray, and user-defined classes unless they are specifically made immutable.
The following are some immutable Python objects — string, tuple, int, float, bool and bytes.
Mutable objects like lists, as stated earlier, are able to be changed after they are created. Creating a list is as simple as making a variable name and binding it to a list object. If I assign y to x, y will have the same id as x. I can change x by appending 4 to it and y will be affected, showing that they are the same object.
After appending 4 to x both x and y have the same id as they had before the append. This shows that the list was changed in place, retaining it’s id.If I use the list method ‘del’ to delete x, y is un affected and it’s object is safe.
If I add 3 to list x, y is no longer the same as x as seen above. The last example shows that list x and y can be the same but have different id’s.
The fact that x and y have different id’s even though they are the same is important to show how Python mutable objects act differently than immutable objects. Below shows how Python handles immutable objects like ints in contrast to mutable lists.
X and y have the same id even though they were created independently.
The example above shows that unlike lists, when the variable copy z of x is created and later 1 is added to z, x stays 1 and z is updated. The important thing to understand is that immutable objects are quicker to access than mutable objects but changing them requires creating a copy, using more memory.
How are mutable and immutable objects handled in functions?
The picture above shows that the immutable int x is unchanged by the function add1. X remains 1.
The above picture show how a mutable list is changed by the function addl. It changes from [1, 2] to [1, 2, 3] but the id of the list object is the same after the function as it was before.