Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mutable and Immutable in Python with Example

In this tutorial, we will learn about the meaning of mutable and immutable objects in Python with the help of examples.

We know that everything in Python is an Object. For example, objects or relation between objects represent all the data in a Python program.

Every object in Python has three characteristics. They are:

  • Identity
  • Data type
  • Value

An object’s identity never changes once it has created. That is, it is unchangeable. It refers to the address of an object in the computer’s memory.

The is operator compares the identity of two objects and the id() function returns a unique identification value (as an integer) of the object stored in the memory. This unique identification value represents the identity of an object.

An object’s data type refers to the type of object that is created. Integer, list, string, etc. are examples of an object’s data type. It also defines the types of values that an object can take.

Python provides a function named type() that returns an object’s type (which is an object itself). Like an object’s identity, the type of an object is also unchangeable.

Mutable and Immutable Object’s Value in Python


Object’s id and type cannot be changed once it has been created, only the value of some objects can change. There are two types of an object’s values or data in Python. They are:

  • Mutable data type
  • Immutable data type

Let us understand each one with the help of some examples.

Mutable Data type in Python


The term mutable means changeable. An object that value or data can change during the execution of a program is called a mutable object or mutable data type. The values of a mutable object can change after it has created.

In other words, we can change the value of a mutable variable after it has created. The examples of Python’s mutable data types are as:

  • List
  • Set
  • Dictionary
  • Bytearray
  • Array

The values of these data types in Python can change after their assignment or creation. When the value of a mutable object is changed, the Python interpreter does not reallocate its memory.

Examples of Mutable Data types


Example 1:

Let’s take an example program to demonstrate a list is a mutable data type in Python.

# Creating a list of values. 
list = ['cat', 'dog', 'goat', 'cow']
print('Original list:',list)
print('Id of original list:',id(list))

# Performing append operation in the current list.
list.append('Buffalo')
# Printing the list after the append operation.
print('List after appending a value: ',list)
print('Id of list after operation:',id(list))

# Removing a value from the list.
list.remove('dog')
# Printing the list after the remove operation.
print('List after removing a value:',list)
print('Id after remove a value:',id(list))
Output:
      Original list: ['cat', 'dog', 'goat', 'cow']
      Id of original list: 1171325498496
      List after appending a value:  ['cat', 'dog', 'goat', 'cow', 'Buffalo']
      Id of list after operation: 1171325498496
      List after removing a value: ['cat', 'goat', 'cow', 'Buffalo']
      Id after remove a value: 1171325498496

In the above program, we have created a list of values and performed multiple operations to demonstrate that a list is a mutable object whose values we can change.

Initially, we created a dummy list and printed the values of list and its id using id() function. Then, we appended a value to the current list, and printed the updated list and its id.

As you will notice, that list’s value has changed, but its identity remains the same (1171325498496). This shows that a list in Python is a mutable object whose values can be changed after creation.


Example 2:

Let’s write a program in which we will change the value of a list by using assignment operator in Python.

# Creating a list of values.
list = [20, 40, 60, 80, 100]
print('Original list:',list)
print('Id of original list:',id(list))

# Changing the value of list.
list[2] = 50
print('Updated list:',list)
print('Id of updated list:',id(list))
Output:
       Original list: [20, 40, 60, 80, 100]
       Id of original list: 2625015100544
       Updated list: [20, 40, 50, 80, 100]
       Id of updated list: 2625015100544


Example 3:

Let’s take an example program in which we will concatenate a new list into the old list using + operator.

# Creating a list of values.
list = [20, 40]
print('Original list:',list)
print("Original list's id:",id(list))

# Adding a list of values into old list.
list = [20, 40] + [60, 80]
print('New list:',list)
print("New list's id:",id(list))
Output:
      Original list: [20, 40]
      Original list's id: 1882487698560
      New list: [20, 40, 60, 80]
      New list's id: 1882487986304

As you can observe in the above program code, list concatenation creates a new list with a new identity (i.e. new memory address). When it happens, the garbage collector removes the old list from the memory because it is garbage.


Example 4:

Let’s take an example program to demonstrate a set is a mutable data type in Python.

# Creating a set of values.
my_set = {10, 20, 30}
# Printing set and its id.
print('Original set:',my_set)
print("Original set's id:",id(my_set))

# Adding a new value in the set.
my_set.add(15)
# Printing the set after the add operation.
print("Set after adding a value:",my_set)
print("Set's is after adding value:",id(my_set))
Output:
      Original set: {10, 20, 30}
      Original set's id: 1999656034912
      Set after adding a value: {10, 20, 30, 15}
      Set's is after adding value: 1999656034912

Example 5:

Let’s take an example to demonstrate a dictionary is a mutable data type in Python.

# Creating a dictionary.
my_dict = {"State": "Jharkhand", "Capital": "Ranchi"}
print('Original dictionary:',my_dict)
print("Original dictionary's id:",id(my_dict))

# Adding new key-value pair to the current dictionary.
my_dict['Country'] = "India"
print("Dictionary after adding a new key-value pair:",my_dict)
print("Dictionary's id after adding:",id(my_dict))
Output:
       Original dictionary: {'State': 'Jharkhand', 'Capital': 'Ranchi'}
       Original dictionary's id: 1864151513472
       Dictionary after adding a new key-value pair: {'State': 'Jharkhand', 'Capital': 'Ranchi', 'Country': 'India'}
       Dictionary's id after adding: 1864151513472

Immutable Data types in Python


The term Immutable means unchangeable. An object that value or data cannot change in its place after initialization or assignment during the execution of a program is called an immutable object or immutable data type.

The values of an immutable object cannot change after it has created. In other words, we cannot change the value of an immutable variable after it has created.

Examples of Python’s immutable data types or objects or variables are as follows:

  • Integers
  • Floating-point numbers
  • Boolean
  • Strings
  • Tuples
  • Frozen set
  • Bytes

The values of these data types in Python cannot modify after their assignment or initialization. When the value of an immutable object modify, the Python interpreter always allocates a new memory location.

Examples of Immutable Data types


Example 6:

# Creating a string.
str = 'Hello'
print('Original string:',str)
print("Id:",id(str))

# Modifying the value in existing string, but Python will create new string object. 
str = 'Good bye'
print('New string:',str)
print("Id:",id(str))
Output:
       Original string: Hello
       Id: 2171413179952
       New string: Good bye
       Id: 2171413182960

From the above code, it seems that whenever we override the value of variable, it might look like we are changing the object’s value. Actually, it is not happening.

Here, we are not changing the object’s value from “Hello” to “Good bye”. Actually, the reference variable str has only switched to refer from the “Hello” object to “Good bye” object.

Both are two different string objects having two different identities. Both string objects have different memory locations or ids.

This shows that string is an immutable object, meaning that whenever we try to modify a string object’s value, Python interpreter always allocates a new memory location with a new address. It never changes the string object’s value in the existing place. Attempting to modify the value of string is not allowed in Python.

Exception to Immutability in Python


A tuple is an immutable sequence object that encloses the values in parentheses and cannot be any change in them once it has been created. Let’s take an example of it.

Example 7:

# Creating a tuple.
my_tuple = (20, 30)
print("Original tuple:",my_tuple)
print("Id:",id(my_tuple))

my_tuple = (20, 30, 40, 50)
print("Tuple after adding values:",my_tuple)
print("Id:",id(my_tuple))
Output:
      Original tuple: (20, 30)
      Id: 1453123462144
      Tuple after adding values: (20, 30, 40, 50)
      Id: 1453123747040

As you can see in the above code, when we have attempted to modify tuple with some new values, Python created a new tuple object in the new memory location. Attempting to modify the tuple in place with value assignment is not allowed in Python.


However, if a tuple contains a mutable object and that changes its value, the value of tuple object also changes. In other words, without creating a new tuple object, we can modify a mutable object inside an immutable tuple in place. Let’s take an example of it.

Example 8:

# Creating a tuple that contains a list (mutable object).
my_tuple = (20, 30, [40, 50, 60])
print("Original tuple:",my_tuple)
print("Id:",id(my_tuple))

# Adding a value in the mutable list inside immutable existing tuple.
my_tuple[2].append(70)
print("Tuple after adding a new value in the list:",my_tuple)
print("Id:",id(my_tuple))
Output:
       Original tuple: (20, 30, [40, 50, 60])
       Id: 1866609292224
       Tuple after adding a new value in the list: (20, 30, [40, 50, 60, 70])
       Id: 1866609292224

As you can see in the above program, we can modify the mutable list inside an existing immutable tuple. Python does not allocate a new memory location when we have modified the mutable list inside immutable tuple. Both tuple objects have the same memory address, meaning that tuple still refers to the same object.

Difference between Mutable and Immutable Objects


There are the following differences between mutable and immutable objects in Python. They are:

(a) A mutable object’s state or values can be changed after it has created, whereas an immutable object’s state or values cannot be changed once created.

(b) Examples of mutable objects are list, set, and dictionary. Whereas, examples of immutable objects are int, float, complex, string, tuple, etc.

(c) Mutable objects are not thread-safe in nature, whereas immutable objects are considered as thread-safe in nature

(d) Mutable object’s values are easy to change as compared to immutable objects.

(e) Immutable objects provides faster access as compared to mutable objects

(f) Mutable objects are useful when we need to change frequently in the existing object. Whereas, immutable objects are best suitable when we are sure that we don’t need to change them frequently at any situation.


In this tutorial, you have learned about mutable and immutable data types in Python with examples. Hope that you will have understood the basic concepts of mutable and immutable objects and practiced all example programs.
Thanks for reading!!!

The post Mutable and Immutable in Python with Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Mutable and Immutable in Python with Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×