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.

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().

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

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)

  

# Adding element to the set

myset.add(“d”)

print(myset)

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 PG Diploma in Data Science and upskill yourself for the future.

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN DATA SCIENCE
Learn More

Leave a comment

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

×