What are mutable and immutable types in Python?
A mutable object can be changed after it is created, and an immutable object cannot. When you “change” an immutable value, Python actually creates a new object.
| Mutable | Immutable |
|---|---|
| list, dict, set | int, float, bool, str, tuple, frozenset |
numbers = [1, 2]
numbers.append(3)
print(numbers)
text = "hi"
print(text.upper())
print(text)
text[0] = "H"
Output:
Tutorials Class - Output Window
[1, 2, 3]
HI
hi
TypeError: 'str' object does not support item assignment
The list was changed in place, but the string stayed the same, and upper() gave a new string. This matters when you pass a list to a function, because the function can change the original list. See Python Data Types.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |