Mutable and Immutable in Python

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

The objects which can change itself are termed as Mutable Objects while on the other hand, those objects which can't change itself are termed as Immutable Objects.

Introduction to Mutable and Immutable in Python

Everything in python is considered an object. When we instantiate an object a unique id is assigned to it. We can't change the type of object but we can change the value of the object. For example, we set variable a as a list, now we can't change variable a from list to tuple/dictionary but we can change the values in that list.

So, there are two types of objects in python. One, those objects which can change their internal state (the data/content inside those objects) i.e. they can be changed with the help of predefined functions or methods while on the other hand, those objects which can't change their internal state(the data/content inside the objects).

Broadly speaking python objects are bifurcated into two types :

  • Mutable Objects
  • Immutable Objects

Mutable Objects in Python

Mutable means those objects which can change themselves after we instantiate them. There are several methods and functions by which we can change the mutable objects. By using those methods and functions the original objects get modified.

While doing any changes to the mutable objects the memory at which those objects are stored remains the same. This is explained in different sections Mutable Objects read along to know more.

Click here, to learn more about Objects in Python.

Example of Mutable Objects

  • List
  • Dictionary
  • Set

Immutable Objects in Python

Immutable means those objects which can't change themselves after we initialize them. There are no methods and functions which can be used to modify those immutable objects. We have to convert those immutable objects to the mutable once and then we can modify those objects.

While doing any changes to the immutable objects, the memory at which these objects were stored during initialization, gets updated. This is explained in different sections Immutable Objects read along to know more.

Example of Immutable Objects

  • int
  • float
  • String
  • Tuple
  • Frozen Set

Example of Mutable Objects in Python

List

List are mutable in nature, it means that we can change the items of list either by using the assignment operator or using the indexing operator.

Let's see example for that

Example

Output

  • ['hi', 'bye', 52, True, 2.3]
  • ['hi', 'see u later', 52, True, 2.3]

Explanation

  • We created a list and add some values to it.
  • We then use the assignment operator in Python, to assign the value at first index.
  • Then, We print the updated list(in the original list) and we see that the value at index 1 got changed.
  • This shows that Lists are mutable in nature.

Dictionary

Dictionaries are mutable in nature, so we can update dictionaries by using the inbuilt function (update).

Let's see an example for that:

Example

Output

  • {1: 'google', 2: 'firefox', 3: 'opera'}
  • {1: 'google', 2: 'firefox', 3: 'opera', 4: 'Ms Edge'}

Explanation

  • We created a dictionary and add some values to it.
  • We create a variable and add a key:value pair to it.
  • Then, We use the update function to add the newly created key:value pair to the dictionary.
  • Finally, we print the dictionary and saw that the newly created key:value pair gets added to the original list.
  • This shows that Dictionaries are mutable in nature.

Set

Set are mutable in nature, so we can update sets by using the inbuilt function (update).

Lets see example for that:

Example

Output

  • {1, 2}
  • {1, 2, 'b', 'a'}

Explanation

  • We created a set and add some values to it.
  • We create a variable and add some more set values to it.
  • Then, We use the update function to add the newly created set to the initial set.
  • Finally, we print the set and saw that the newly created set gets added to the original set.
  • This shows that Sets are mutable in nature.

Example of Immutable Objects in Python

int

int is immutable in nature, so we can't change or update the int data-type.

As we read earlier, that immutable objects change their memory address when they get updated.

Let's see example of that:

Example

Output

  • memory address before updating: 9789600
  • memory address after updating: 9789920

Explanation

  • We assigned some integer value to a variable.
  • Then, we print the id of that variable.
  • After updating the variable, we again print the id of that variable.
  • The output for both times is different.
  • This implies that the integers are immutable in nature as another object of integer was created and referenced on updating its value.

float

float is immutable in nature, so we can't change or update the float data-type.

As we read earlier, that immutable objects change their memory address when they get updated.

Let's see example of that:

Example

Output

  • memory address before updating: 140664386693680
  • memory address after updating: 140664386693712

Explanation

  • We assigned some float values to a variable.
  • Then, we print the id of that variable.
  • After updating the variable, we again print the id of that variable.
  • The output for both times is different.
  • This implies that the floats are immutable in nature as another object of integer was created and referenced on updating its value.

String

Strings are immutable in nature, so we can't append or update anything in the string. While updating any part of the string we got some errors like strings are not mutable in nature.

Let's see an example of that:

Example

Output

  • stringVariable[0] = 'bye'
  • TypeError: 'str' object does not support item assignment

Explanation

  • We assigned some string values to a variable.
  • Then, we try to update the string using the item assignment operator.
  • After updating the variable, when we print the string it gives the error item assignment not supported.
  • This implies that strings are immutable in nature.

Tuple

Tuples are also immutable in nature, so we can't append or update anything in the tuples. While updating any item in tuple we got some errors like strings is not mutable in nature.

Let's see example of that:

Example

Output

  • tupVariable[1] = 5
  • TypeError: 'tuple' object does not support item assignment

Explanation

  • We assigned some values to the tuple.
  • Then, we try to update the tuple using the item assignment operator.
  • After updating the variable, when we print the string it gives the error item assignment not supported.
  • This implies that tuples are immutable in nature.

FrozenSet

Frozensets are like sets in python but they are immutable in nature. While elements in the set can be modified any time, but this can't be done in frozenset. So, we can't append or update anything in the frozenSet. While updating any item in frozenSet we got some errors like frozenSets is not mutable in nature.

Let's see example of that:

Example

Output

  • frozenset Object is : frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
  • fnum[1] = 10
  • TypeError: frozenset object does not support item assignment

Explanation

  • We assigned some values to the tuple.
  • Then we convert the tuple to the frozenset by using the frozenset function.
  • Then, we try to update the frozenset by using the item assignment operator.
  • After updating the variable, when we print the string it gives the error item assignment not supported.
  • This shows that frozensets are immutable in nature.

Examples of Mutable and Immutable Objects

Suppose we have to create an application for storing the information regarding the subjects opted by the students. While creating such an application we must keep in mind that we must use those objects which can be modified later as per the requirement.

So for this application, we must use Mutable objects like List instead of Immutable Objects like tuple to store the name of all the subjects opted by a student.

If we use tuple(immutable object) here, we can't change the tuple again. If we have to update the subject list of any student then we need to create a new tuple which takes a lot of memory and is not a good practice.

But, if we use list(mutable object) here, then we have a function like an append(to add data), pop(to remove data), item assignment operators, and many more to update the data inside the list. This approach doesn't take extra memory because it updates the original list.

Example

Output

['subject1', 'subject2', 'subject3', 'subject4']

Explanation

  • With the help of append(), we have added a new subject to the subject list of the student.
  • After printing the subjects we saw that the original list gets modified and new subjects get added to it.

Check out this article to learn more about Append () in Python.

Conclusion

  • In this article, we studied about what are the Mutable and Immutable objects in python.
  • Then, we deeply studied mutable objects and examples of Mutable Objects.
  • After that, we go to immutable objects and then see the example of Immutable Objects.
  • Finally, we saw some examples of how mutable and immutable objects work.

Learn More: