Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 10 of 10 · Data Types and Data Structures
Interview question

What is the difference between mutable and immutable data types? - Data Types and Data Structures Mutable और immutable data types में क्या अंतर है?

Answer
TypeMutableImmutable
Exampleslist, dict, setint, str, tuple, frozenset
Change in placeYesNo
Dict keyNoYes
PerformanceSlowerFaster
# 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')
TypeMutableImmutable
Exampleslist, dict, setint, 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'  # Error

Was this answer clear?