Python Mutable vs Immutable Objects
Learn how Python Mutable vs Immutable Objects works and which is better
Published
Python Mutable vs Immutable Objects
In Python Mutable objects are following. Also, the custom classes generally we create are mutable.
- list
- dict
- set
Immutable objects are faster to access but expensive to change because python has to recreate a copy. In Python Tuple is Immutable, and primitive data types are also immutable.
- Tuple
- Int
- Float
- Complex
- Bytes
Meanwhile mutable objects are easy to change. It’s recommended to use Mutable objects when add, update into content needed.
Check the following example to update an list object which is mutable. It means that it apply changes to existing object in memory.
Mutable Example
countries = ["USA", "Canada", "Australia"]
print (countries)
countries [1] = "Findland"
print (countries)
Immutable Example
Remember, tuple (immutable objects) are faster to access.
babiesName = ("Martha", "Stuart", "Jim")
print(babiesName[0])
However, if you try to update an item inside tuple it will give you an error.
babiesName = ("Martha", "Stuart", "Jim")
babiesName[0] = "Angela"
print(babiesName[0])
So, there is a work around to to update tuple. First convert tuple into list and update it after that reconvert list to tuple. Although, it’s not the good practice.
babiesName = ("Martha", "Stuart", "Jim")
babiesNameList = list (babiesName)
babiesNameList[0] = "Angela"
babiesName = tuple(babiesNameList)
print(babiesName)