Difference between mutable and immutable in python?


Python defines variety of data types of objects. These objects are stored in memory and object mutability depends upon the type, like Lists and Dictionaries are mutable it means that we can change their content without changing their identity. Other objects like Integers, Floats, Strings, and Tuples have no provision to change there assigned value for an index.

List is mutable: Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. Lists are mutable, and hence, they can be altered even after their creation.

Example

#Write a python program to print list of a number?
list=[1,2,3,4,5]
print(list)

Output

[1,2,3,4,5]

List is a collection which is ordered and changeable. Allows duplicate members.

Example

list=[1,2,3,4,5]
list[0] ='a'
print(list)

Output

['a', 2, 3, 4, 5]

While running the program, assigning the zero based index with the value of '1' can be assigned a value of 'a' which is mutable(can be modified)

Tuple is immutable: A tuple is a collection which is ordered and unchangeable, does not allow duplicate members. In Python tuples are written with round or inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them.

Example

#Write a python program to print tuple of a number?
Tuple=(10,20,30)
print(tuple)

Output

(10,20,30)

Tuple is ordered and unchangeable(cannot be modified).

Example

tuple=(10,20,30)
tuple[0]=50
print(tuple)

Output

TypeError Traceback (most recent call last)
in
1 my_yuple = (10, 20, 30)
----> 2 my_yuple[0] = 50
3 print(my_yuple)

TypeError: 'tuple' object does not support item assignment

While assigning the zero based index with the value of '50' throws an exception, because it is already assigned a value of '10' which is immutable(cannot be modified).

Sri
Sri

Updated on: 09-Sep-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements