Mutable vs Immutable Data Objects in Python

Syed Shahzaib Ali
3 min readAug 7, 2022

In this short article, let's understand the basic difference between mutable and immutable data types in Python. “Mutable” comes from the word “Mutate” which means to “change in form”.

So, simply a mutable object is one that has the flexibility to be edited or changed easily. On the other, immutable objects follow the opposite approach and they strictly oppose any change. In order to make a change, you need to create a copy of immutable objects which is a memory expensive operation.

In python, if a particular object is being passed onto a function. Depending on the type of that object, if that is mutable, its reference will be passed and changes can be made in a function that will reflect outside the function as well. Whereas, if the object is immutable, it will pass as a value and no changes will be reflected outside the function.

Mutable Objects in Python

  • Lists
  • Sets
  • Dictionaries
  • Byte Array

Features:

  • Use when there’s a need to modify objects
  • Due to call by reference nature, they are memory efficient

Immutable Objects in Python

  • Integer
  • Float
  • Bytes
  • Strings
  • Tuples
  • Immutable Sets (Frozen Sets)

Features

  • Always use it when you need to make sure that objects shouldn’t be modified in any way
  • Changing immutable objects are expensive, it requires copying that is a memory inefficient approach

Let's Consider an Example:

In the following example, I have initialized two different objects as mutable (list) and immutable (tuple).

Initializing Mutable and Immutable Objects

Further, we defined a function to modify the value of each type of data object.

Defining Modifier Functions for List and Tuple type Objects

If we try to modify the values of a mutable object (i.e. list), you can observe that it updated the values of the outer object as well because it was passed as a reference and the function made changes to that reference.

Modifying Mutable Object (List)

On the other hand, if you try to update the values of a tuple object, it will not update the values of the source object because it was passed as the value instead.

Modifying Immutable Object (Tuple)

Bonus Point:

If you want to check if a particular object is mutable or immutable. Simply call a hash function on that. Immutable objects are hashable but mutable ones aren’t.

hash(myList) > will output some hash number/value

hash(myTuple) > will throw an error

I hope, it was helpful. Happy Learning :)

--

--

Syed Shahzaib Ali

Lead AI Expert| Data Scientist | Natural Language Processing Expert | xIBM