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.

Check out all Trending Python Tutorial Concepts. 

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

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905229
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions & Answers [For Freshers & Experienced]
20916
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5067
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5172
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17639
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10801
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80749
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
139107
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

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