Middle
Can you explain in more detail why these data types are considered mutable? Can you give specific examples of mutable data types and explain how they are modified?
sobes.tech AI
Answer from AI
In Python, mutable data types are objects whose state can be changed after creation. Immutable objects cannot be changed — any operations create a new object.
Examples of mutable types:
- list — elements can be added, removed, modified.
- dict — key-value pairs can be added, removed, modified.
- set — elements can be added and removed.
How they change:
lst = [1, 2, 3]
lst.append(4) # lst is now [1, 2, 3, 4]
d = {'a': 1}
d['b'] = 2 # d is now {'a': 1, 'b': 2}
s = {1, 2}
s.add(3) # s is now {1, 2, 3}
Mutability means that the object retains its identity (id) in memory, but its contents change.
In contrast, immutable types (int, float, str, tuple) create a new object when modified:
x = 10
print(id(x))
x += 1
print(id(x)) # id has changed because a new object was created
Mutability is important for understanding object behavior when passing to functions, copying, and working with multithreading.