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 runtime and it can't be changed afterwards. However, its state can be changed if it is a mutable object.
Immutable Objects
Immutable Objects are of in-built datatypes like int, float, bool, string (str) and tuple. In simple words, an immutable object can’t be changed after it is created.
Example 1: 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 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: 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 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
Mutable Objects are of type Python list, Python dict, or Python set. Custom classes are generally mutable.
Are Lists Mutable?
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.
Example 1: Add and Remove items from a list in Python
Here, a list is modified by adding, inserting, removing and deleting elements. Lists are mutable, which means their contents can be changed after creation using methods such as append(), insert(), extend(), remove() and pop().
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
Dictionaries are mutable, so we can directly update the value associated with a key after the dictionary is created.
my_dict = {"name": "Ram", "age": 25}
my_dict["age"] = 37
print(my_dict)
Output
{'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.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Output
{1, 2, 3, 4}
Python's Mutable vs Immutable
- Mutable and immutable objects behave differently in Python. Immutable objects cannot be modified, so any change creates a new object. Mutable objects can be changed in place after they are created.
- 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 contains a string and a list. While the tuple itself is immutable, mutable objects inside it (such as lists) can still be modified. In general, built-in scalar types are immutable, whereas container types are often mutable.
| Feature | Mutable Objects | Immutable Objects |
|---|---|---|
| Can be modified after creation | Yes | No |
| Object identity remains the same after modification | Yes | No (a new object is created when changed) |
| Examples | list, dict, set | int, float, bool, str, tuple |
| Suitable for | Data that changes frequently | Fixed or constant data |