Professional Documents
Culture Documents
Difference Between Mutable and Immutable in Python
Difference Between Mutable and Immutable in Python
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.
All the variables having the following data types are mutable.
list
dict
set
bytearray
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.
3 str_Output = ""
5 string_Output += str(data)
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.
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