Junior
What are mutable and immutable data types in Python and give examples?
sobes.tech AI
Answer from AI
In Python, data types are divided into mutable and immutable.
Mutable data types can be changed after creation. When an object of a mutable type is modified, the object itself remains the same, but its contents change.
Immutable data types cannot be changed after creation. Any operation that appears to modify an immutable object actually creates a new object.
Examples:
| Type | Mutable / Immutable |
|---|---|
int |
Immutable |
float |
Immutable |
str |
Immutable |
bool |
Immutable |
tuple |
Immutable |
list |
Mutable |
dict |
Mutable |
set |
Mutable |
frozenset |
Immutable |
Code examples:
-
Immutable
int:a = 5 b = a print(id(a)) # Print object id a += 1 print(id(a)) # Print id of the same object after "change" - it is different print(b) # b remains the same -
Mutable
list:list1 = [1, 2, 3] list2 = list1 print(id(list1)) # Print list id list1.append(4) print(id(list1)) # Print list id after adding an element - it is the same print(list2) # list2 also changed
The difference between them matters for variable behavior and argument passing in functions. When passing a mutable object to a function, changes inside the function will be visible outside. When passing an immutable object, changes inside the function will create a new local object.