Mutable and Immutable Objects in Python

In this Python article, we will discuss every detail of the mutable and immutable objects, how and why to use them along with various implementation examples.

1. What is the use of Mutable and Immutable Object in Python?

If the internal state of any object can be changed or can be mutated then it is termed as a Mutable object.

On the other side, if an object does not permit any possible changes in the object after it has been initialized then it is termed as an Immutable object.

An object is mutable if it allows change in its value. This type of object keeps a collection of data that may require changes.

Python Mutable and Immutable Objects
Python Mutable and Immutable Objects

Examples of mutable of built-in type are:

An object is immutable if no changes can be made over time. If this type of object is once created, then its value is permanent.

Examples of immutable objects of in-built data types are:

  • int
  • float
  • bool
  • string
  • Unicode
  • tuple

Read More about Data Types in Python

Let’s take an example to understand the mutable objects.

countries = ["India", "Germany", "US"]

for item in countries:
  print(item, end=" ")

print(hex(id(countries)))
print("\n")

countries.append("Russia")

for item in countries:
  print(item, end=" ")

print(hex(id(countries)))
Output
India Germany US 0x7f2d7e623248
India Germany US Russia 0x7f2d7e623248

In the above example, we have added a new item to the countries list but the hexadecimal value of the id still remains the same. This indicates that the new value was made a change to the existing object and has not created a new object.

Let’s take an example to understand the immutable object.

tuple_values = ("x", "y", "z")
tuple_values[2] = "w"
print(tuple_values)
Output
Traceback (most recent call last):
File "main.py", line 3, in 
tuple_values[2] = "w"
TypeError: 'tuple' object does not support item assignment

2. Features of Mutable and Immutable Objects

During the lifetime of a program, we make a lot of changes to the existing dataset. For such scenarios, we need mutable objects in places where we want to permit any changes or updates.

For example, the shopkeeper keeps a record of available products and the record is been updated with any new sales or any new supplies.

Immutable objects provide effectiveness when we want to use some constant values and are sure that this data is never gonna be change.

For example, if a shopkeeper wants to have a python script for the profit, loss, and sales, then some of the fields that can be immutable are Currency, shopId, data from previous days, etc.

Once an immutable object is created, the stored value is sealed and ensures that the data is not overwritten/updated by any threads.

An immutable object also helps in reducing bugs because we remove the chances of accidentally updating that value.

Immutable objects also help new developers understand the code better by declaring the nature of the object and ensuring that initialized values will never be updated.

  • The handling of mutable and immutable objects is somewhat different in Python. Immutable things can be accessed more quickly and costly to modify since they entail copying, whereas Mutable things can easily be modified.
  • When changing the size or content of the object, it is suggested that mutable objects be used.

3. Exceptions in Immutability in Python

Immutability also has certain exceptions. It can be said that not every immutable object is really immutable. Certainly, this statement will create doubts in the mind. Let us just take an example to understand this.

As we now know that the tuple objects are immutable. But the tuple contains a sequence of values with unalterable bindings to objects.

Consider a tuple ‘excep_tuple’.

excep_tuple = (‘Codingeek’,['P','y','t','h','o','n'],[1,5,10,15],[3.67,4.76,9.03])

The above tuple contains data from various data types. Starting with a string that is immutable, followed by three lists that are definitely mutable. As tuple itself is immutable and cannot be altered, however, the list inside it can be altered.

Hence, the data values of an immutable object are unalterable but its constituent elements can alter their values.

3.1. Mix of Mutable and Immutable objects

Let’s take an example to understand the exceptions in immutability and the mix of mutable and immutable objects.

subjects = (['Physics', 'Chemistry', 'Maths'], [
            'Physics', 'Chemistry', 'Biology'])

print(subjects)
# location ofcreated object in the memory address
print(hex(id(subjects)))

# Changing subject inside the 1st element
subjects[0][1] = "English"

print(subjects)
print(hex(id(subjects)))
Output
(['Physics', 'Chemistry', 'Maths'], ['Physics', 'Chemistry', 'Biology'])
0x7f34da964448
(['Physics', 'English', 'Maths'], ['Physics', 'Chemistry', 'Biology'])
0x7f34da964448

Here, in the above example, it is clearly visible that the object ‘subjects’ is immutable as being declared as a type of tuple. Inside the tuple, there are two lists and we tried to change the list’s values(as the list is mutable). However, the object reference of the tuple was not altered but the mutation was made on the referenced object.

This means that an immutable object can not update the behavior of its nested mutable objects and vice versa.


4. Conclusion

Finally, to sum up, in this article we have covered and learned everything about mutable and immutable objects in python along with their use and their implementation, we have covered:

  • How to use the mutable and the immutable object, what is mutable and immutable objects in Python with examples?
  • Different features of Mutable and Immutable Objects in Python and their implementation in code.
  • Various applications of Mutable and Immutable Objects in python.
  • Certain exceptions in Immutability in Python or simply the exception in immutable objects. What is the exception in immutable obejcts with example?

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x