Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconMutable vs. Immutable Objects in Python: Learn The Real Difference

Mutable vs. Immutable Objects in Python: Learn The Real Difference

Last updated:
6th Oct, 2020
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Mutable vs. Immutable Objects in Python: Learn The Real Difference

The hype around functional programming and immutable objects are often confused. But, if you want a better resume with Python knowledge, the objects are all you need to concentrate on. The importance of immutable objects is a heavily debated topic among developers, and yet it remains inconclusive.

Python has become quite popular among developers. According to a JetBrains survey, 93% of software testing professionals prefer Python as a primary language. There is no doubt that Python has been a forefront programming language, not just in machine learning or artificial intelligence, but also in application development lately. 

The most confusing element of Python is the object. Whether to choose a mutable or immutable object in Python remains a point of discussion. So, let’s understand the difference. If you want to learn more about data science, check out our data science programs

Read: Career Opportunities in Python

Mutable and Immutable in Python

Any object in Python whose internal state is changeable can be called a mutable. Similarly, the objects with a static state or ones that can’t be changed are immutable. The difference may seem simple, but the effect of both these objects is different in programming. 

To understand the type of objects in Python, we need to understand the structure of language. Let’s consider an example, 

age = 62

print(id(age)) # id

print(type(age)) # type

print(age) # value

[Out:]

25356154

<class ‘int’>

62

The example states that Python has some key elements in the structure. These elements are:

  • An ID(Identity)
  • A type
  • A value

Whether the value changes or not determines the type of object in python- “mutable or immutable.” It is also essential for programmers to learn that the identity and the class never change. The ID is a unique identifier that helps recognize the object in Python. 

Let’s take another example to understand:

age = 62

print(id(age))

print(type(age))

print(age)

age = 63

print(age)

print(id(age))

[Out:]

25356154

<class ‘int’>

62

63

25356166

Here, in the first instance, you may wonder whether the change in age indicates a mutable object. But it is just an integer. The ‘int’ class is immutable and co-related to the name ‘age.’ So, when we change the age from 62 to 63, it points towards the ‘int’ class. 

When you type 63, another object is created differently from 62. It is an object that points to ‘age’ in a different location with another unique ID. 

Now that you know the primary difference, the first thing that will come to your mind is: which type of objects are mutable and immutable in Python?

Also Read: Python Developer Salary in India

Mutable Types

We already know by now that mutable values can change after creation. Types of mutable values in Python are:

  • Lists
  • Byte arrays
  • Sets
  • Dictionaries

Lists

List data in Python are mutable. Let’s take an example,

my_list = [1,2,3]

print(my_list)

print(id(my_list))

>>> [1,2,3]

>>> 1863010210504

my_list.append(4)

print(my_list)

print(id(my_list))

>>> [1,2,3,4]

>>> 1863010210504

Here, you can observe the value of the list changes from [1,2,3] to [1,2,3,4]. The append() method used here adds a single item ‘4’. It means that the process does not return with an entirely new list and instead changes the original one. You can observe the increase in the size of the list after executing append().

Explore our Popular Data Science Online Courses

Byte arrays

Python supports many different data objects. The most popular of them are byte arrays and bytes. Here, we are looking at the bytearray() function that returns with an array of bytes. It is an object that can be changed, that too in the range of integers 0 to 256. 

At the same time, there is bytes() function in Python. It is immutable and can’t be changed. The object supports values ranging from 0 to 255. Here is an example for the bytearray() object.

b = bytearray(b’python’)

print(id(b))

b.replace(b’p’, b’P’)

print(id(b))

[Out:]

139963525979808

139963525979808

upGrad’s Exclusive Data Science Webinar for you –

Watch our Webinar on How to Build Digital & Data Mindset?

 

Sets

A set is a random collection of the different data types which are changeable and devoid of duplication. It represents the mathematical side of the data set. The most significant benefit of using a set in Python for the programmers is checking how an element is contained. At the same time, it is not the same in a list. As the data is random and lacks indexing, access is not as simple as it may be in an indexed list. 

Here is an example for the set in Python:

# Python program to

# demonstrate sets

 # Same as {“a”, “b”, “c”}

myset = set([“a”, “b”, “c”])

print(myset)

 

Top Data Science Skills to Learn to upskill

# Adding element to the set

myset.add(“d”)

print(myset)

Read our popular Data Science Articles

Dictionaries

Dictionaries are placing the data in a map-like sequence. Developers can use a Dictionary through a curly {} tag set apart with a comma. It has two pairs of values: one is the key, and the other is key values. The data type in dictionaries varies and also can be duplicated. The key should be immutable and a key value to be mutable.

Hee is an example for the dictionaries in Python:

# Creating a Dictionary 

# with Integer Keys

Dict = {1: ‘meeks’, 2: ‘For’, 3: ‘meeks’}

print(“\nDictionary with the use of Integer Keys: “)

print(Dict)

  

# Creating a Dictionary 

# with Mixed keys

Dict = {‘Name’: ‘meeks’, 1: [1, 2, 3, 4]}

print(“\nDictionary with the use of Mixed Keys: “)

print(Dict)

Immutables in Python

Immutables are rigid and can’t be changed. Some of the immutable data types used in Python are:

  • Numeric data types
  • String
  • Bytes
  • Frozen sets
  • Tuples

Numeric data types

We already saw in the first example of this article how integers are immutable. Apart from the numbers, decimals, fractions, booleans, and complex numbers, all are immutable.

String

Unicode code points are a unique character in Python. They are a representation of the textual data type in Python. Here, such immutable sequences are used for str objects, also known as String. 

Immutable Bytes

If you want to store textual data, you need to encode it. Such encoding creates bytes objects that are immutable. The structure of immutable bytes is similar to Strings.

Frozen Sets

Frozen sets are not so different from their mutable counterparts. But, they are quite limited and not used as much as mutable sets. Frozen sets are equally crucial for performance-related tests and operations.

Tuples

Tuples are sequences of random Python objects. It can be integers, frozen sets, and any other object. Here is an example:

g = (1, 3, 5)

print(id(g))

g = (42, )

print(id(g))

 

[Out:]

139952252343784

139952253457184

Must Read: Important Python Developer Skills

Conclusion

Python is one of the most innovative programming languages, and its fundamental knowledge can help you boost your career. We saw differences in mutable and immutable in Python. The difference between these objects is quite essential for developers to understand, as it is one of the most asked questions in interviews.

If you are curious about learning python, data science to be in the front of fast-paced technological advancements, check out upGrad & IIIT-B’s Executive PG Programme in Data Science and upskill yourself for the future.

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 some examples of Mutable Objects?

When something is mutable, it is alterable or has the capacity to change. 'Mutable' in Python refers to an object's capability to modify its values. These are the items that contain a collection of data. Lists, Sets, and Dictionaries are some examples of objects which are a part of Python's Mutable objects.

2What are some examples of Immutable objects?

When there is no possibility of change through time, it is said to be immutable. In Python, an object is said to be immutable if its value cannot be modified over time. The value of these items is fixed once they are created. The examples of Immutable objects in Python are Numbers (Integer, Rational, Float, Decimal, Complex & Booleans), Strings, Tuples, and Frozen Sets.

3What are objects in Python?

An object is a basic building component in an object-oriented language. Objects include integers, texts, floating-point numbers, arrays, and dictionaries. An object is, more specifically, any single integer or text. The number 12 is an object, as is the phrase 'hello, world,' and a list is an object that may store additional objects. Every object has a type, which determines what you can do with the object.

Explore Free Courses

Suggested Blogs

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905106
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 &#038; Answers [For Freshers &#038; Experienced]
20864
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
5064
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)
5152
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]
17605
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 &#038; Techniques
10776
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
80614
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 &#038; Types [With Examples]
139007
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