Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Difference between mutable and immutable

in Python:
The variable, for which we can change the value is called mutable variable.
The variable, for which we can not change the value is immutable variable.

In the case of Python, both types of variables are available.

All the variables having the following data types are mutable.

 list

 dict

 set

 bytearray

 user-defined classes (unless specifically made immutable)

Now examples of Immutable Data type in Python.

All the variables having the following data types are immutable.

 int

 float

 decimal

 complex

 bool

 string

 tuple

 range

 frozenset

 bytes
You can easily check the datatype of any variable in Python.

Why is String Immutable if it can be


Concatenated?
Talking about the String mutability, many geeks are confused.
1 list_Name =["Bob", "Alley", "Mike"];

3 str_Output = ""

4 for data in list_Name:

5 string_Output += str(data)

Look at the above program. It is a simple program that concatenates the


string. You might be saying; it should be mutable as the string is getting
updated.

But internally, it does not update the string; rather it creates the new string.
This is all because the string is immutable. It creates a third string by
concatenating two strings.

And this is the reason, this code of concatenation is not efficient as it creates
new string every time you call for concatenation.

If you are iterating through the concatenation, lots of memory can be wasted
for creating a temporary string and throwing it out after concatenation.

So here is a simple and most effective solution…

1 list_Name =["Bob", "Alley", "Mike"];


2
3 # Another way is to use a
4 #list comprehension technique in Python
5 "".join([str(data) for data in list_Name])
It concatenates all the list object values and then converts it into a string. As
concatenation occurs at the list (mutable), no new object is created.

Why is Tuple Immutable Data Type in


Python?
If list and dictionary are mutable variables, it’s really confusing as a tuple is
immutable. But it is.

Take a list (mutable object) and a tuple (immutable object). Compare what it
can be after updating values.

Let’s take an example to prove it by comparing the tuple with the list.
1
2
3 # Create a list variable
list_Num = [5, 7, 9, 11]
4
5 # Create a tuple variable (initialize with the same values)
6 tup_Num = (5, 7, 9, 11)
7
8 # print the list
9 list_Num
[5, 7, 9, 11] # output
10
11 # print the tuple
12 tup_Num
13 (5, 7, 9, 11) # output
14
15 # alter the list (change any value in the list)
16 list_Num [1] = 6 # success
17
# alter the tuple (change any value in the tuple)
18 tup_Num [1] = 4 # error
19
20 # print the list again
21 list_Num
22 [5, 6, 9, 11] # There is a change in value; so called mutable.
23
# print the tuple
24 tup_Num
25 (5, 7, 9, 11) # None of the values are changed; so it is immutable.
26
27

You might also like