×

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

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.