Junior — Middle
Explain what it means to be able to modify the contents of objects in Python.
sobes.tech AI
Answer from AI
In Python, objects can be mutable or immutable. The ability to modify the contents of an object means that after creating the object, you can change its internal state without creating a new object.
For example, lists (list) and dictionaries (dict) are mutable objects. You can add, delete, or modify elements within them:
my_list = [1, 2, 3]
my_list.append(4) # the list has changed
print(my_list) # [1, 2, 3, 4]
On the other hand, strings (str) and tuples (tuple) are immutable objects. Any operation that appears to modify them actually creates a new object:
s = "hello"
s = s + " world" # a new string is created
print(s) # 'hello world'
Understanding mutability is important for proper state management and avoiding unexpected side effects in a program.