Understanding Mutable and Immutable Values in Python

Before going into the topic, let us get an overview of what mutable and immutable objects are from the perspective of Python.

Mutable Value in Python

Mutable values are the values that can be modified after being created. This implies that you can modify the values without producing a new value. Below is an illustration of mutable and immutable values implemented in Python.

Example:

Python3




# Python mutable value (List)
demo_list = [1, 2, 3, 4, 5]
print("Original List:", demo_list)
  
demo_list[0] = 10
print("Modified List:", demo_list)


Output:

Original List: [1, 2, 3, 4, 5]
Modified List: [10, 2, 3, 4, 5]

Immutable Value in Python

Contrary to mutable values in Python, there is an immutable value that cannot be edited or modified as shown below:

Example:

Python3




# Python immutable values (Tuple)
demo_tuple = (1, 2, 3, 4, 5)
print("Original Tuple", demo_tuple)
  
demo_tuple[0] = 10
print("Modified Tuple", demo_tuple)


Output:

 

Use mutable default value as an argument in Python

Python lets you set default values ​​for its parameters when you define a function or method. If no argument for this parameter is passed to the function while calling it in such situations default value will be used. If the default values ​​are mutable or modifiable (lists, dictionaries, etc.), they can be modified within the function and those modifications will persist across function calls.

However, using mutable default values ​​as arguments in Python can lead to unexpected behavior. This article explores the concept of volatile defaults, the potential problems they can cause, and how to use them effectively.

Similar Reads

Understanding Mutable and Immutable Values in Python

Before going into the topic, let us get an overview of what mutable and immutable objects are from the perspective of Python....

What are Mutable Default Values

...

Contact Us