Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconWhat Is Mutable And Immutable In Python?

What Is Mutable And Immutable In Python?

Last updated:
14th Jun, 2023
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
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.

What in Python are mutable and immutable?

What is mutable and immutable in Python? This is a common query, especially among beginners. An object that can be changed after creation is referred to as mutable in Python. Immutable, on the other hand, in Python refers to an object that cannot be changed after it is created. Let’s examine each category in greater detail to gain a better understanding of this idea.

Variables in Python can store several sorts of data, and these data types can be divided into mutable and immutable categories. Python programming is most effective when the idea of mutability is understood. In this review, we’ll look at immutable and mutable meaning in Python, how they differ, and some examples of both.

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.  

Python’s mutable data types

In Python, mutable data types permit changes after initialization. Lists, sets, and dictionaries are just a few examples of changeable data structures that are frequently used. These data types support alterations including element addition, removal, and change.

Let’s take a Python list as an example:

numbers = [1, 2, 3, 4]

The list ‘numbers’ in this case can be altered by including, deleting, or replacing entries. By directly accessing an existing element’s index, we can edit it or insert a new element using the append() method.

A dictionary is another illustration:

student = {‘name’: ‘John’, ‘age’: 20}

In this situation, we can change the values connected to the keys or expand the dictionary by adding new key-value pairs.

Python’s immutable data types:

Immutable data types in Python are those that cannot be modified after creation, as the name implies. Strings, tuples, and numbers (including integers, floats, and booleans) are examples of immutable data types.

Let’s think about a string:

message = “Hello, World!”

The string ‘message’ cannot be changed directly in this situation. We can generate a new string with the needed adjustment, but we cannot change a character at a certain index.

Tuples are also immutable.

coordinates = (10, 20)

The tuple’s values are fixed once they are generated. A new tuple must be made if the values need to be changed.

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.

What separates mutable from immutable?

The way mutable and immutable data types handle modifications is their main distinction. Mutable data types alter an existing item in place, whereas immutable data types produce a new object when changed. This divergence has effects on how variables behave in Python programmes and how memory is managed.

Since they avoid unintentional changes, immutable objects are regarded as safer. Particularly when handling concurrent operations or sending data between functions, they provide data integrity. On the other side, mutable objects offer adaptability and permit effective adjustments.

Writing effective and error-free code in Python requires an understanding of the concept of mutability. Lists, sets, and dictionaries are examples of mutable data types that can be changed after creation, whereas strings, tuples, and numbers are examples of immutable data types that cannot be altered. Understanding the distinctions between mutable and immutable data types enables developers to choose data types carefully and steer clear of any problems brought on by unintentional changes. Keep in mind that the performance and dependability of your Python programmes can be significantly impacted by selecting the correct data type based on its mutability.

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

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

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.

2In Python, what are mutable and immutable data types?

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.

3Are lists mutable in Python?

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.

Explore Free Courses

Suggested Blogs

17 Must Read Pandas Interview Questions & Answers [For Freshers & Experienced]
50298
Pandas is a BSD-licensed and open-source Python library offering high-performance, easy-to-use data structures, and data analysis tools. Python with P
Read More

by Rohit Sharma

04 Oct 2023

13 Interesting Data Structure Project Ideas and Topics For Beginners [2023]
223767
In the world of computer science, data structure refers to the format that contains a collection of data values, their relationships, and the function
Read More

by Rohit Sharma

03 Oct 2023

How To Remove Excel Duplicate: Deleting Duplicates in Excel
1328
Ever wondered how to tackle the pesky issue of duplicate data in Microsoft Excel? Well, you’re not alone! Excel has become a powerhouse tool, es
Read More

by Keerthi Shivakumar

26 Sep 2023

Python Free Online Course with Certification [2023]
122362
Summary: In this Article, you will learn about python free online course with certification. Programming with Python: Introduction for Beginners Lea
Read More

by Rohit Sharma

20 Sep 2023

Information Retrieval System Explained: Types, Comparison & Components
53130
An information retrieval (IR) system is a set of algorithms that facilitate the relevance of displayed documents to searched queries. In simple words,
Read More

by Rohit Sharma

19 Sep 2023

40 Scripting Interview Questions & Answers [For Freshers & Experienced]
13621
For those of you who use any of the major operating systems regularly, you will be interacting with one of the two most critical components of an oper
Read More

by Rohit Sharma

17 Sep 2023

Best Capstone Project Ideas & Topics in 2023
2582
Capstone projects have become a cornerstone of modern education, offering students a unique opportunity to bridge the gap between academic learning an
Read More

by Rohit Sharma

15 Sep 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
295563
Summary: In this Article, you will learn about 4 Types of Data Qualitative Data Type Nominal Ordinal Quantitative Data Type Discrete Continuous R
Read More

by Rohit Sharma

14 Sep 2023

Data Science Course Eligibility Criteria: Syllabus, Skills & Subjects
46334
Summary: In this article, you will learn in detail about Course Eligibility Demand Who is Eligible? Curriculum Subjects & Skills The Science Beh
Read More

by Rohit Sharma

14 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon