×

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects

As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data in the form of fields which is commonly known as attributes. In an Object-oriented programming language, the OOPs have two main keys without using them OOPs can't be achieved. Below are the main keys.

  1. Class 
  2. Objects

And the main pillars of the Object-Oriented Programming language are:

  • Polymorphism
  • Encapsulation
  • Abstraction
  • Inheritance

What is class and object?

Class:

Class is mostly called the user-defined data type where user can define their own functions and methods. The class is also known as the blueprint of the object. which guides the object to the path and the function to be performed. Class doesn't define any data to the object. In Object-oriented programming, class plays a very important role that is why it is known as the basic unit of OOPs programming.

Object:

Whereas, the object is classified as a variable that is the instance of the class. The Object uses to store class functions and methods, and the data. that means the Object can store multiple data and data structures.

The objects are of two types that are mutable objects and Immutable objects

What is Mutable objects?

Mutable objects refer to those objects whose values or the content can be changed after initialization as per the requirement and usage. Mutable objects are classified as List, Set, Dictionary, and User-Defined Classes. For example, we declare a list with the values as "Red", "Green", and "Orange" and want to change the last value with "Blue" and First value with "Black". So, List, Set, and Dictionary allow to change the values. But the rest don't allow the same.

How to declare List, Set, Dictionary, and User-Defined Classes in Python?

In Python, Declaring the variable with a specific data type is not a big deal. Hence same goes with the List, Set, Dictionary, and user-defined data types. No heavy and fancy code require to declare all this let us see how to declare all of them with the Syntax of each:

 #list
# syntax for list
List_name=["Value1","Value2"]
#declaration of list
List=["Orange","Apple","Mango"]
#Set
#syntax for set
set_name = {"Value1","Value2"}
#declaration of Set
set= {"Orange","Apple","Mango"}
#Dictionary
#syntax for Dictionary
Dict_name={ 'repres1':"Value1", 'repres2':"Value2"}
#declaration of Dictionary
Dict={'Orange':"Orange",'Red':"Apple",'Yellow':"Mango"}
#user defined Class
#syntax for user defined Class
class class_name():
    #class block
#declaration of user defined Class
class classes():
    print("Hello World!") 

What is Immutable objects?

As per the name, it's clear that it is the opposite of mutable objects. That means Immutable objects refer to those whose values or content cannot change after initialization as per the requirement of the user or programmer. In Python, Number, String, Tuples, Frozen Sets, Bytes, and User-Defined Classes are the types of Immutable objects. 

Let us understand this with example, for example if we declare a tuple with some value and want to change it after the initialization. So it will show error to us.

How to declare Tuples in python?

 #tuples
#Syntax for tuples
tuple_name=("values","values")
#declaration of tuples
tuple=("one","Two","Three") 

Programs

Programs1: To check Immutable object(Tuples)

 # Python code to test 
#immutable object
tuple1 = ("Black", "Blue", "Orange", "Red")
tuple1[0] = "Green"
print(tuple1) 

Output:

 Traceback (most recent call last):
  File "c:\Users\Dodo\OneDrive\Desktop\desktop\sachin\JavaTpoint\dictionary\practical.py", line 4, in <module>
    tuple1[0] = "Green"
TypeError: 'tuple' object does not support item assignment 

Programs2: To check Immutable object(String)

 # Python code to test that 
# strings are immutable 
message = "Welcome In JavaTpoint"
message[0] = 'Hii'
print(message) 

Output:

 Traceback (most recent call last):
  File "c:\Users\Dodo\OneDrive\Desktop\desktop\sachin\JavaTpoint\dictionary\practical.py", line 4, in <module>
    message[0] = 'Hii'
TypeError: 'str' object does not support item assignment 

Programs3: To check Mutable object(List)

 # Python code to test that
# lists are mutable
color = ["Red", "Blue", "Green"]
print(color)
color[0] = "Black"
color[-1] = "Orange"
print(color) 

Output:

 ['Red', 'Blue', 'Green']
['Black', 'Blue', 'Orange'] 

Difference Between Mutable and Immutable Objects:

BasisMutable ObjectsImmutable Objects
MeaningMutable objects refer to those objects whose values or the content can be changed after initialization as per the requirement and usage  Immutable objects refer to those whose values or content cannot change after initialization as per the requirement of the user or programmer  
Type  All the classes and its classes are mutable by default by their nature.  String and all wrapper class are immutable by their nature.
Final Class  To create a Mutable object, the class don’t require to be final  To create a Immutable object, the class require to be final
ExamplesList, Set, Dictionary, and User-Defined Classes  Number, String, Tuples, Frozen Sets, Bytes, and User-Defined Classes  

Related Topics

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

AES CTR Python

Python Programming Language  Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.