Junior
Give an example of mutable and immutable data types.
sobes.tech AI
Answer from AI
Mutable data types can be changed after creation, immutable ones cannot.
Examples:
Mutable:
- Lists
- Dictionaries
- Sets
# Example of changing a list
my_list = [1, 2, 3]
my_list[0] = 100 # List element changed
print(my_list) # [100, 2, 3]
# Example of changing a dictionary
my_dict = {'a': 1, 'b': 2}
my_dict['a'] = 100 # Value by key changed
my_dict['c'] = 3 # New element added
print(my_dict) # {'a': 100, 'b': 2, 'c': 3}
Immutable:
- Numbers (Integer, Float, Boolean)
- Strings
- Tuples
# Example of "changing" a string - actually a new string is created
my_string = "hello"
# my_string[0] = "H" # Error, strings are immutable
new_string = "H" + my_string[1:] # Creating a new string
print(new_string) # Hello
# Example of "changing" a tuple - actually a new tuple is created
my_tuple = (1, 2, 3)
# my_tuple[0] = 100 # Error, tuples are immutable
new_tuple = (100,) + my_tuple[1:] # Creating a new tuple
print(new_tuple) # (100, 2, 3)