Interview question
What is the difference between mutable and immutable data types? - Data Types and Data Structures Mutable और immutable data types में क्या अंतर है?
Answer
| Type | Mutable | Immutable |
|---|---|---|
| Examples | list, dict, set | int, str, tuple, frozenset |
| Change in place | Yes | No |
| Dict key | No | Yes |
| Performance | Slower | Faster |
# Mutable - can change in place
my_list = [1, 2, 3]
my_list[0] = 99 # Changes original
my_dict = {'a': 1}
my_dict['a'] = 2 # Changes original
# Immutable - cannot change, create new
my_tuple = (1, 2, 3)
# my_tuple[0] = 99 # TypeError
my_str = 'hello'
# my_str[0] = 'H' # TypeError
new_str = 'H' + my_str[1:] # Create new string
# Immutable types as dict keys
my_dict = {
(1, 2): 'tuple key', # OK
'string': 'value', # OK
42: 'number' # OK
}
# Cannot use mutable types as keys
try:
my_dict[[1, 2]] = 'list key' # TypeError
except TypeError:
print('Lists cannot be keys')| Type | Mutable | Immutable |
|---|---|---|
| Examples | list, dict, set | int, str, tuple |
| Change कर सकते हैं | हाँ | नहीं |
| Dict key | नहीं | हाँ |
my_list = [1, 2, 3]
my_list[0] = 99 # बदल जाता है
my_tuple = (1, 2, 3)
# my_tuple[0] = 99 # Error
# Dictionary keys
my_dict = {(1, 2): 'value'} # काम करता है
# my_dict[[1, 2]] = 'value' # ErrorWas this answer clear?