Python 3 — Mutable, Immutable… everything is object!

Reese Hicks
3 min readSep 30, 2020

Because everything in Python is an object, one eventually will learn that one main difference between objects is that they can either be mutable or immutable. You see, every variable in Python holds an object instance, and when that object is created, it is assigned a unique object ID. This ID is fixed at runtime, meaning that it’s type will always be the same. However, depending on the type (if its type is mutable or immutable), the object’s state may be able to be changed. So, to put it simply, a mutable object can be changed after it is created, and a immutable object can not be changed. Lets look into this a bit further, to get a better understanding of this concept.

As seen in the above example of built-in object types, integer, float, bool, string, tuple, and unicode are immutable, while the types list, set, and dictionary are mutable. Custom classes, such as those written by a developer, will be mutable as well.

So, why does all this matter?

Well, for one, immutable objects are much quicker to access, however, mutable objects are great to use in the case you may need to change its value or size. Such may be the case when using integers or dictionaries. Immutable objects are used when one needs to make sure the object you just made will always be the same. Having an object set for good can be very useful.

Identity:

Each object has an identity, a type and a value. Identities are most easily thought of as an object’s address in your computer’s memory. It never changes once it has been created. The identities of objects can be compared using the is operator, and the id() function returns an integer, which represents the object’s identity (this is its memory address).

Type:

Unchangeable too, is an object's type. Type determines the kinds of operations the object supports. It also defines possible values for that object. The type() function returns an object’s type. Now, the value of some objects can change, and they are called mutable. Objects who’s values can not change after being created are called immutable. See? It all comes full circle. But this is where it can sometimes become tricky, because the value of an immutable object can contain a reference to a mutable object (called a container). This might frighten you, but THAT value may be able to change too. So, simply saying that an object who’s value can not change is not always 100% accurate. The manual for Python like to describe it as being more “subtle”. An object’s ability to change, or “mutability” is defined by the object’s type, as listed above.

>>> s1 = “reeseHicks”
>>> s2 = s1
>>> print(s1 == s2)
True

--

--