Mutable vs Immutable Objects in Python
Last Updated :
21 May, 2024
In Python, Every variable in Python holds an instance of an object. There are two types of objects in Python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can't be changed afterward. However, its state can be changed if it is a mutable object.
Mutable and Immutable Objects in Python
Let us see what are Python's Mutable vs Immutable Types in Python.
Immutable Objects in Python
Immutable Objects are of in-built datatypes like int, float, bool, string, Unicode, and tuple. In simple words, an immutable object can’t be changed after it is created.
Example 1: In this example, we will take a tuple and try to modify its value at a particular index and print it. As a tuple is an immutable object, it will throw an error when we try to modify it.
Python
# Python code to test that
# tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
Example 2: In this example, we will take a Python string and try to modify its value. Similar to the tuple, strings are immutable and will throw an error.
Python
# Python code to test that
# strings are immutable
message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Error:
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
Mutable Objects in Python
Mutable Objects are of type Python list, Python dict, or Python set. Custom classes are generally mutable.
Are Lists Mutable in Python?
Yes, Lists are mutable in Python. We can add or remove elements from the list. In Python, mutability refers to the capability of an object to be changed or modified after its creation.
In Python, lists are a widely used data structure that allows the storage and manipulation of a collection of items. One of the key characteristics of lists is their mutability, which refers to the ability to modify the list after it has been created.
Example 1: Add and Remove items from a list in Python
In this example, we will take a Python List object and try to modify its value using the index. A list in Python is mutable, that is, it allows us to change its value once it is created. Lists have the ability to add and remove elements dynamically. Lists provide methods such as append(),insert(),extend(),remove() and pop().
Python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
my_list.insert(1, 5)
print(my_list)
my_list.remove(2)
print(my_list)
popped_element = my_list.pop(0)
print(my_list)
print(popped_element)
Output
[1, 2, 3, 4]
[1, 5, 2, 3, 4]
[1, 5, 3, 4]
[5, 3, 4]
1
Example 2: Modify item from a dictionary in Python
Here is an example of dictionary that are mutable i.e., we can make changes in the Dictionary.
Python
my_dict = {"name": "Ram", "age": 25}
new_dict = my_dict
new_dict["age"] = 37
print(my_dict)
print(new_dict)
Output
{'name': 'Ram', 'age': 37}
{'name': 'Ram', 'age': 37}
Example 3: Modify item from a Set in Python
Here is an example of Set that are mutable i.e., we can make changes in the set.
Python
my_set = {1, 2, 3}
new_set = my_set
new_set.add(4)
print(my_set)
print(new_set)
Output
{1, 2, 3, 4}
{1, 2, 3, 4}
Python's Mutable vs Immutable
- Mutable and immutable objects are handled differently in Python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy. Whereas mutable objects are easy to change.
- The use of mutable objects is recommended when there is a need to change the size or content of the object.
- Exception: However, there is an exception in immutability as well. We know that a tuple in Python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects. Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can't change their value. But the contents of the list can change. The tuple itself isn’t mutable but contains items that are mutable. As a rule of thumb, generally, Primitive-like types are probably immutable, and Customized Container-like types are mostly mutable.
Similar Reads
Are Sets Mutable in Python? Yes, sets are mutable in Python. This means that you can modify the contents of a set after it has been created. You can add or remove elements from a set but like dictionaries, the elements within a set must be immutable types.Example of Mutability in SetsAdding Elements to a SetYou can add element
2 min read
Are Dictionaries Mutable or Immutable in Python In Python, dictionaries are mutable. This means that you can modify the contents of a dictionary after it has been created. You can add, update or remove key-value pairs in a dictionary which makes it a flexible and dynamic data structure.What Does It Mean for Dictionaries to Be Mutable?Being mutabl
2 min read
Python Object Comparison : "is" vs "==" In Python, both is and == are used for comparison, but they serve different purposes:== (Equality Operator) â Compares values of two objects.is (Identity Operator) â Compares memory location of two objects.Pythona = [1,2,3] b = [1,2,3] print(a == b) print(a is b) OutputTrue False Explanation: a and
2 min read
Why do we Need Immutables in Python ? When a Novice steps into the Programming world and kicks off to learn about different concepts of it and yet eventually reaching to the Data Structures and Algorithms, learning and implementing them, but one or the other way he/she tends to read once and forget about the Immutable object. Mutable an
4 min read
Creating Instance Objects in Python In Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the
3 min read
Are Lists Mutable in Python? Yes, lists are mutable in Python. This means that once a list is created, we can modify it by adding, removing or changing elements without creating a new list.Let's explore some examples that demonstrate how lists can be modified in Python:Changing Elements in a ListSince lists are mutable, you can
3 min read