Sobes.tech
Junior

What is the difference between mutable and immutable data types in Python?

sobes.tech AI

Answer from AI

Difference in the ability to change the state of an object after its creation.

Mutable:

  • The internal state of the object can be changed after its creation.
  • When the object is changed, its id remains the same.
  • Used to represent data that can change during the program's execution.
// Example of a mutable type: list
my_list = [1, 2, 3]
print(id(my_list)) // Outputs the id of the list object
my_list.append(4)
print(my_list)   // Outputs [1, 2, 3, 4]
print(id(my_list)) // Outputs the same id

Immutable:

  • The internal state of the object cannot be changed after its creation.
  • When "changing" the object, a new object is created, and its id changes.
  • Used to represent data that should not change.
// Example of an immutable type: tuple
my_tuple = (1, 2, 3)
print(id(my_tuple)) // Outputs the id of the tuple object
// my_tuple.append(4) // Will raise TypeError: 'tuple' object has no attribute 'append'
my_tuple = my_tuple + (4,) // Creates a new tuple
print(my_tuple)   // Outputs (1, 2, 3, 4)
print(id(my_tuple)) // Outputs the new id

Main data types by mutability:

Data Type Mutability
list Mutable
dict Mutable
set Mutable
bytearray Mutable
int Immutable
float Immutable
str Immutable
tuple Immutable
frozenset Immutable
bytes Immutable
bool Immutable