Name mutable and immutable objects in Python


In this article, we will explain to you the mutable and immutable objects in python.

Python considers everything to be an object. A unique id is assigned to it when we instantiate an object. We cannot modify the type of object, but we may change its value. For example, if we set variable a to be a list, we can't change it to a tuple/dictionary, but we may modify the entries in that list.

In Python, there are two kinds of objects. On the one hand, there are objects that can change their internal state (the data/content inside the objects), i.e. they can be changed using predefined functions or methods, and on the other hand, there are objects that cannot change their internal state (the data/content inside the objects).

In Python, there are 2 types of objects −

  • mutable objects

  • immutable objects.

To conclude the difference, mutable objects can change their state or content, but immutable objects cannot.

Mutable objects

Mutable objects are those that can be modified after we instantiate them. We can alter the mutable objects using a variety of methods and functions. The original objects are modified when certain methods and functions are used.

While making modifications to mutable objects, the memory in which those objects are stored remains unchanged.

Examples of mutable objects in python are

  • List

  • Dictionary

  • Set

List

Lists are mutable, which implies that we can change the elements in the list using either the assignment or indexing operators.

Example

# input list inputList = ['hello', 'tutorialspoint', 'python', 1] # printing the original input list print("The original input list:", inputList) # modifying the list element at index 2 using indexing inputList[2]= 'welcome' # printing input list after modifying print("Input list after modification:", inputList)

Output

On executing, the above program will generate the following output −

The original input list: ['hello', 'tutorialspoint', 'python', 1]
Input list after modification: ['hello', 'tutorialspoint', 'welcome', 1]

We took a list with some random values and then changed one of the list's elements with another random value; because lists are mutable data types, the value of the element is changed without raising any errors.

Dictionary

Since dictionaries are mutable, we can update them using the built-in function update().

Example

# input list inputList = ['hello', 'tutorialspoint', 'python', 1] # printing the original input list print("The original input list:", inputList) # modifying the element at index 2 using indexing inputList[2]= 'welcome' # printing input list after modifying print("Input list after modification:", inputList)

Output

On executing, the above program will generate the following output −

The original input list: ['hello', 'tutorialspoint', 'python', 1]
Input list after modification: ['hello', 'tutorialspoint', 'welcome', 1]

Immutable Objects

These are built-in types such as int, float, bool, string, unicode, Frozen Set and tuple. In other words, an immutable object cannot be modified once it has been created.

When you make changes to immutable objects, the memory where they were stored during initialization is updated.

int

Since the int data type is immutable, we cannot modify or update it.

As previously stated, immutable objects change their memory address when they are updated.

Example

# input number inputNumber = 5 # printing the memory address of the int variable print('Before updating, memory address = ', id(inputNumber)) # here we are updating an int object by assigning a new value to it. # changing the same input number variable by assigning a new value to it inputNumber = 10 # printing the memory address of the int variable after updating using id() function print('After updating, memory address = ', id(inputNumber))

Output

On executing, the above program will generate the following output

Before updating, memory address =  140509421819936
After updating, memory address =  140509421820096

Similarly, the float datatype also changes its memory address value after updating.

tuple

Tuples are likewise immutable, which means we can't append or update anything in them. While modifying any item in a tuple, we get errors 'tuple' object does not support item assignment.

Example

# input tuple inputTuple = ('hello', 'tutorialspoint', 'python') # printing the original input tuple print("The original input tuple:", inputTuple) # modifying the tuple element at index 2 using indexing inputTuple[2]= 'welcome' # printing input tuple after modifying print("Input tuple after modification:", inputTuple)

Output

The original input tuple: ('hello', 'tutorialspoint', 'python')
Traceback (most recent call last):
File "main.py", line 6, in <module>
inputTuple[2]= 'welcome'
TypeError: 'tuple' object does not support item assignment

We took a tuple with some random values and then changed the element of the list with another random value, because tuples are immutable data types, the value of the element is not changed and an exception is thrown.

String

Because strings are immutable, we cannot append or update anything in them. While modifying any part of the string, we encountered problems indicating that strings are not mutable in nature.

Example

# input string inputString = 'Welcome to tutorialspoint python' # changing the string character at index 1 inputString[1] = 'a' print(inputString)

Output

Traceback (most recent call last):
File "main.py", line 4, in <module>
inputString[1] = 'a'
TypeError: 'str' object does not support item assignment

Mutable vs Immutable

Mutable Immutable
state of the object can be changed once created state of the object cannot be changed once created
Mutable objects are NOT thread-safe Immutable objects are thread-safe
Since mutable objects are not final, the programmer can keep altering them while still using the same objects. Before creating an immutable object, it is important to make the class final.

Conclusion

We learned about mutable and immutable objects in this section, as well as examples of mutable and immutable objects with their source codes. We also learned about the differences between mutable and immutable objects.

Updated on: 15-Sep-2022

460 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements