What are the differences between mutable and
immutable data types in Python
In Python, data types are categorized into two main types based on their ability to be modified
after creation: mutable and immutable.
Mutable Data Types
Mutable data types are those whose values can be changed after creation. These types allow
modifications such as adding, removing, or updating elements without creating a new object.
Common examples of mutable data types in Python include:
Lists (list): Ordered collections of elements that can be modified.
my_list = [1, 2, 3]
my_list.append(4) # my_list becomes [1, 2, 3, 4]
Dictionaries (dict): Unordered collections of key-value pairs where values can be updated
or new pairs can be added.
my_dict = {"name": "John"}
my_dict["age"] = 30 # my_dict becomes {"name": "John", "age": 30}
Sets (set): Unordered collections of unique elements where elements can be added or
removed.
my_set = {1, 2, 3}
my_set.add(4) # my_set becomes {1, 2, 3, 4}
User-defined classes: These can be mutable depending on their implementation.
Immutable Data Types
Immutable data types are those whose values cannot be changed after creation. Any attempt
to modify an immutable object results in the creation of a new object. Common examples of
immutable data types in Python include:
Integers (int), Floating-point Numbers (float), and Complex Numbers (complex):
Numbers that cannot be altered once assigned.
x = 5
x = x + 1 # Creates a new integer object with the value 6
Strings (str): Sequences of characters that cannot be modified in place.
s = "Hello"
s = s + " World" # Creates a new string object with the value "Hello World"
Tuples (tuple): Ordered collections of elements that cannot be modified.
t = (1, 2, 3)
# Attempting t[^0] = 4 will raise a TypeError
Boolean (bool): Logical values that cannot be changed once assigned.
is_admin = True
is_admin = False # Creates a new boolean object with the value False
Ranges (range): Sequences of numbers that cannot be modified.
r = range(1, 4)
# Attempting to modify r will raise an error
Key Differences
Modifiability: Mutable types can be changed after creation, while immutable types cannot.
Memory Usage: Immutable types create new objects when modified, which can lead to
increased memory usage if not managed properly.
Use Cases: Immutable types are beneficial for ensuring data integrity and consistency,
while mutable types provide flexibility for dynamic data structures.
Understanding these differences is crucial for efficient and bug-free programming in Python.
⁂