Programs

What Is Mutable And Immutable In Python?

In Python, every variable holds an instance of any object in two kinds, i.e. mutable and immutable. A unique object id is assigned to an object whenever it is instantiated. The runtime defines the object type and cannot be changed later. 

However, the changeable one is a mutable object. When we say mutable, it means the internal object state can be mutated. Simultaneously, the object state incapable of changing after creation is an immutable object. Both mutable and immutable states are integral to the data structure of Python.

The feature of object mutability in Python makes it a dynamically typed language. Mutable and Immutable in Python is quite essential as a concept but are often confused due to their intransitive nature of immutability. 

Let’s find out all about them and the key differences.

Check out our data science online courses to upskill yourself

Top Data Science Skills to Learn to upskill

Mutable State In Python

The word ‘Mutable’ directly translates to ‘changeable’ or something that can be ‘mutated’. It defines an object open to changes, and in Python, ‘mutable’ relates to an object’s ability to change values. These objects often store data collection and contain built-in type lists, sets, dictionaries and user-defined classes.  

Immutable Definition State In Python

Immutable in Python is when you cannot change the object type over time. If it is not possible to alter the value of an object in Python, it is known as an immutable object. Once an immutable object is created, its value remains permanent and unchangeable. Immutable built-in type objects are numbers, strings, tuples, frozen sets, and user-defined classes.

Objects in Python

Before we delve deep into mutability and immutability in Python, let us first learn what objects are. In Python, everything is considered an object, and each object has three attributes:

  • Identity: This refers to the object’s address in the computer’s memory.
  • Type: This refers to the object type that is made. For instance, integer, string, list and the like. 
  • Value: This refers to the value that the object stores. For example, List=[5,6,7] would store the numbers 5, 6 and 7.

Even if the ID and Type of an object are not open to change after creation, the values are open to alterations for Mutable objects.

Mutable Objects in Python

Mutable objects are the objects in Python that can be mutated or changed. Codes serve better in teaching about the implementation of these objects. Therefore, let us look at a few codes and try to understand mutable objects better:

  • For making a list containing the names of fruits

fruits= [‘Mango’, ‘Papaya’, ‘Orange’]

  • For printing elements from the list of fruits, divided by a comma & space

for fruit in fruits:

    print(fruit, end=’, ’)

Output [1]: Mango, Papaya, Orange

  • For printing the object location that is created in the memory address in a hexadecimal format

Explore our Popular Data Science Online Courses

print(hex(id(fruits)))

Output [2]: 0x1691d7de8c8

  • Adding a new fruit to the list ‘fruits’

fruits.append(‘Grapes’)

  • For printing the elements present in the list ‘fruits’, separated by a comma & space

for fruit in fruits:

    print(fruit, end=’, ’)

 

Output [3]: Mango, Papaya, Orange, Grapes

 

  • For printing the object location created in the memory address in a hexadecimal format

print(hex(id(fruits)))

Output [4]: 0x1691d7de8c8

The example shows that the object’s internal state ‘fruits’ can easily change by adding one more fruit, ‘Grapes’ to it. However, the object’s memory address remains the same, proving that a new object does not need to be created. Rather, the same object could be changed or mutated. This example shows that the object with the reference variable name ‘fruits’, a list type, is mutable.

Immutable Objects in Python

Immutable objects in Python are the objects whose values cannot be changed. Let us follow a simple code to grasp better what immutable objects are and how they work. The code is given below:-

  • For creating a Tuple containing the English name of months

months= ‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’

  • For printing the elements of tuple months

print(months)

Output [1]:  (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’)

  • For printing the object location, which is created in the memory address in a hexadecimal format

print(hex(id(months)))

Output [2]: 0x1691cc35090

  • It is important to note that tuples are immutable; therefore, they fail to include more new elements. Hence, you need to use the merge of tuples with the # + operator to add a new imaginary month in the tuple ‘months’.

months +=  ‘Pythonuary’

  • For printing the elements of tuple ‘months’.

print(months)

Output [3]: (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘Pythonuary’)

  • For printing the object location created in the memory address in a hexadecimal format

print(hex(id(months)))

Output [4]: 0x1691cc8ad68

Read our popular Data Science Articles

This example proves variable names can be easily used for referencing an object, a kind of tuple consisting of eight elements. However, the memory location ID of the old & new tuple is not the same. Hence, the object’s internal state ‘months’ could not be changed. Therefore, the Python program manager created a new object in the memory address. Additionally, the variable name ‘months’ also referenced the new object with nine elements. Hence, proving that the tuple, the object with the reference variable name ‘months’, is an immutable object.

Conclusion

Mutable objects are primarily used for allowing any future updates. On the other hand, immutability also offers many effective and practical applications for various sensitive tasks in a network-centred place, enabling parallel processing. Immutable objects, seal the values and ensure that none of the threads invokes overwrite/update to the data. It is great for writing permanent codes that won’t need changes in future. 

If you are a budding programmer or a data science enthusiast, learning about mutable and immutable objects in Python will prove to help you choose this field as your career. The best way to learn about these is by signing up for the Executive Post Graduate Programme in Data Science on upGrad.

The course is created under expert faculty guidance, delivering in-depth knowledge of trending topics to prepare thousands of learners for a future-proof career.

Q1. What are the significant differences between mutable vs immutable in Python?

Answer: An object’s state or value is open to modification after creation in mutable An object’s state or value is not open to modification after creation in immutable Mutable objects aren’t thread-safe. Immutable objects are completely thread-safe Mutable classes aren’t final. Before creating an immutable object, you must make the class final.

Q2. In Python, what are mutable and immutable data types?

Answer: Mutable data types in Python are list, set, dictionary and user-defined classes and immutable data types are int, decimal, float, bool, tuple, string, and range.

Q3. Are lists mutable in Python?

Answer: In Python, lists are the mutable data types with easily modified elements. Additionally, you can replace the individual elements and even change the order of elements after creating the list.

Want to share this article?

Prepare for the career of the future

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks