Differentiate between mutable and immutable data types in
Python, providing examples of each.
Ans. In Python, data types can be classified as either mutable or immutable based on
whether their values can be changed after they are created. Here's a differentiation
between mutable and immutable data types along with examples of each:
1. Mutable Data Types:
Mutable data types allow modifications to their values after they are created.
Changes to mutable objects directly affect their memory location.
Examples are:
i. Lists: Lists are ordered collections that can be modified by adding,
removing, or changing elements. For example:
my_list = [1, 2, 3]
my_list.append(4)
my_list[1] = 5
ii. Dictionaries: Dictionaries are unordered collections of key-value pairs. The
qualities related with keys can be modified. For example:
my_dict = {'name': 'John', 'age': 25}
my_dict['age'] = 26
2. Immutable Data Types:
Once created the Immutable data types cannot be modified.
Python, providing examples of each.
Ans. In Python, data types can be classified as either mutable or immutable based on
whether their values can be changed after they are created. Here's a differentiation
between mutable and immutable data types along with examples of each:
1. Mutable Data Types:
Mutable data types allow modifications to their values after they are created.
Changes to mutable objects directly affect their memory location.
Examples are:
i. Lists: Lists are ordered collections that can be modified by adding,
removing, or changing elements. For example:
my_list = [1, 2, 3]
my_list.append(4)
my_list[1] = 5
ii. Dictionaries: Dictionaries are unordered collections of key-value pairs. The
qualities related with keys can be modified. For example:
my_dict = {'name': 'John', 'age': 25}
my_dict['age'] = 26
2. Immutable Data Types:
Once created the Immutable data types cannot be modified.