Mutable and Immutable Objects in Python3

Objects are omnipresent in Python. Understanding the ways objects are stored, assigned, and manipulated will allow you to further delve into the world of object-oriented programming while also grasping the holistic essence of Python.

To gather more information about objects, you can use Python’s built-in functions id() and type() :

I assigned my_object to equal 42 and then used both functions to obtain the address — 10056864 — and the type — ‘int’.

A key concept of objects is their mutability. Whether they can be changed (mutable object) or they can’t (immutable object). An example of a mutable object is a list.

In this example, I’m assigning list2 = list1 and by doing so I can change the data of list1 and list2 will point to the same object.

On the other hand, an immutable object such as a tuple cannot be changed and if the example were attempted it would result in this:

Since everything in Python is an object the idea of mutability plays a large role in variable assignment. Assigning multiple variables to the same immutable object will be more efficient at the cost of not being able to edit the data.

As these examples suggest, arguments passed into function are affected by whether they are mutable or immutable. You can use a append() on a mutable list but not on an immutable tuple.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.