Mutable vs Immutable Objects in Python
Last Updated :
21 May, 2024
In Python, Every variable in Python holds an instance of an object. There are two types of objects in Python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterward. However, its state can be changed if it is a mutable object.
Mutable and Immutable Objects in Python
Let us see what are Python’s Mutable vs Immutable Types in Python.
Immutable Objects in Python
Immutable Objects are of in-built datatypes like int, float, bool, string, Unicode, and tuple. In simple words, an immutable object can’t be changed after it is created.
Example 1: In this example, we will take a tuple and try to modify its value at a particular index and print it. As a tuple is an immutable object, it will throw an error when we try to modify it.
Python
# Python code to test that
# tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
Example 2: In this example, we will take a Python string and try to modify its value. Similar to the tuple, strings are immutable and will throw an error.
Python
# Python code to test that
# strings are immutable
message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Error:
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
Mutable Objects in Python
Mutable Objects are of type Python list, Python dict, or Python set. Custom classes are generally mutable.
Are Lists Mutable in Python?
Yes, Lists are mutable in Python. We can add or remove elements from the list. In Python, mutability refers to the capability of an object to be changed or modified after its creation.
In Python, lists are a widely used data structure that allows the storage and manipulation of a collection of items. One of the key characteristics of lists is their mutability, which refers to the ability to modify the list after it has been created.
Example 1: Add and Remove items from a list in Python
In this example, we will take a Python List object and try to modify its value using the index. A list in Python is mutable, that is, it allows us to change its value once it is created. Lists have the ability to add and remove elements dynamically. Lists provide methods such as append(),insert(),extend(),remove() and pop().
Python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
my_list.insert(1, 5)
print(my_list)
my_list.remove(2)
print(my_list)
popped_element = my_list.pop(0)
print(my_list)
print(popped_element)
Output
[1, 2, 3, 4]
[1, 5, 2, 3, 4]
[1, 5, 3, 4]
[5, 3, 4]
1
Example 2: Modify item from a dictionary in Python
Here is an example of dictionary that are mutable i.e., we can make changes in the Dictionary.
Python
my_dict = {"name": "Ram", "age": 25}
new_dict = my_dict
new_dict["age"] = 37
print(my_dict)
print(new_dict)
Output
{'name': 'Ram', 'age': 37}
{'name': 'Ram', 'age': 37}Example 3: Modify item from a Set in Python
Here is an example of Set that are mutable i.e., we can make changes in the set.
Python
my_set = {1, 2, 3}
new_set = my_set
new_set.add(4)
print(my_set)
print(new_set)
Output
{1, 2, 3, 4}
{1, 2, 3, 4}Python’s Mutable vs Immutable
- Mutable and immutable objects are handled differently in Python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy. Whereas mutable objects are easy to change.
- The use of mutable objects is recommended when there is a need to change the size or content of the object.
- Exception: However, there is an exception in immutability as well. We know that a tuple in Python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects. Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change their value. But the contents of the list can change. The tuple itself isn’t mutable but contains items that are mutable. As a rule of thumb, generally, Primitive-like types are probably immutable, and Customized Container-like types are mostly mutable.
Similar Reads
Mutable vs Immutable Objects in Python
In Python, Every variable in Python holds an instance of an object. There are two types of objects in Python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can't be changed afterward.
4 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys. How to Loop Through a Dictionary in PythonThere are multip
6 min read
Instance method in Python
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Python : __delete__ vs __del__
Both __delete__ and __del__ are dunder or magic methods in Python. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. __del__ __del__ is a des
2 min read
Least Astonishment and the Mutable Default Argument in Python
The principle of Least Astonishment (also known as least surprise) is a design guideline that states that a system should behave the way it is intended to behave. It should not change its behavior in an unexpected manner to astonish the user. By following this principle, designers can help to create
3 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the at
3 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
Getter and Setter in Python
In Python, getters and setters are not the same as those in other object-oriented programming languages. Basically, the main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation. Private variables in python are not actually hidden fields like in other obje
4 min read
Advance Features of Python
Python is a high-level, interpreted programming language that has easy syntax. Python codes are compiled line-by-line which makes the debugging of errors much easier and efficient. Python works on almost all types of platforms such as Windows, Mac, Linux, Raspberry Pi, etc. Python supports modules a
7 min read
Polymorphism in Python
Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
7 min read
Understanding Code Reuse and Modularity in Python 3
What is Object Oriented Programming(OOP)? OOP is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. Learn more here, or just Google "OOP".Objects have charact
7 min read
Python __all__
Have you ever used a Python file’s variables after importing (`from F import *`) it into another Python file? In this scenario, every variable from that file can be used in the second file where the import is made. In this article, we'll look at one Python mechanism, called __all__, which allows use
5 min read
Descriptor in Python
Definition of descriptor : Python descriptors are created to manage the attributes of different classes which use the object as reference. In descriptors we used three different methods that are __getters__(), __setters__(), and __delete__(). If any of those methods are defined for an object, it can
5 min read
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input (
4 min read
Difference between copying an object through assignment operator and _.clone() function ?
There are two ways, we can copy the object in javascript, first is by using the assignment operator i.e. '=' and the second is by using the 'clone' function. In this article, we'll discuss what is the difference between both of them. By using the _.clone() function: Both of these methods copy object
2 min read
Shallow copy vs Deep copy in Pandas Series
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially cop
4 min read
Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially cop
4 min read
Why does comparing strings using either '==' or 'is' sometimes produce a different result in Python?
Python offers many ways of checking relations between two objects. Unlike some high-level languages, such as C++, Java, etc., which strictly use conditional operators. The most popular operators for checking equivalence between two operands are the == operator and the is operator. But there exists a
4 min read