Mutable and Immutable DataTypes in Python

Below are the examples by which we can understand more about mutable and immutable data types in Python:

Mutable Data Type

Mutable data types are those data types whose values can be changed once created. In Python, lists, and dictionaries are mutable data types. One can change the value of the list once assigned.

In this example, we have changed the value of the element at index 4, i.e., “e” with “hello”. This reflects that lists in Python are mutable.

Python




list=['a','b','c','d','e','f','g','h']
print("original list ")
print(list)
  
 # changing element at index 4 ,i.e., e to hello
list[4]='hello' 
print("changed list")
print(list)


Output

original list 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
changed list
['a', 'b', 'c', 'd', 'hello', 'f', 'g', 'h']




Immutable DataType

Immutable data types are those data types whose values cannot be changed once created . In Python, string, tuple etc, are immutable data type. One cannot change the value of list once assign.

Python




str= "hello"
print("original  string")
print(str)
  
str[2]="p" #gives an error


Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
str[2]="p" #gives an error
TypeError: 'str' object does not support item assignment

Concept of Mutable Lists in Python

The concept of mutable lists refers to lists whose elements can be modified or changed after the list is created. In programming, a list is a data structure that stores an ordered collection of elements. The mutability of a list determines whether you can modify its contents, such as adding or removing elements, changing the values of existing elements, or reordering the elements. In this article, we will see the concept of mutable lists in Python.

Similar Reads

Mutable and Immutable DataTypes in Python

Below are the examples by which we can understand more about mutable and immutable data types in Python:...

Concept Of Mutable Lists

...

Conclusion

...