Mutable and immutable in Python is an important concept which every Python programmer must be familiar with while learning about Python programming. In the Python Programming language, there are many elements or data structures which cannot be changed or modified once they are created.
The immutable property of the Python program ensures the safety of the sensitive data. In this blog, we will learn everything about Python mutable and immutable elements and properties.
What are Mutable Elements In Python?
There are many data types in Python which can be modified or altered even after creation. In Python these data types can be changed anytime the users want. For example, Lists, dictionaries, sets, and user defined classes are some of the mutable elements in Python programming language.
- It can be changed even after creation.
- Mutable elements require more memory space due to potential changes possible in the element.
- It is used in situations which require dynamic data and information changes.
- For examples, lists, dictionaries, sets, and user defined classes
For example, let us suppose we have a list where we are trying to insert data into the list using predefined methods in the Python list.
my_list = [1, 2, 3, 4, 5, 6]
my_list.append(7) print(my_list) |
Output
![]() |
Write a Python program to modify items kept in a Dictionary in Python.
student = {
“name”: “Alice”, “age”: 21, “course”: “Computer Science” } print(“Original Dictionary:”) print(student) student[“age”] = 22 student[“grade”] = “A” del student[“course”] print(“\nModified Dictionary:”) print(student) |
Output
![]() |
What are Immutable Elements In Python?
Immutable elements in Python are the elements or data types which cannot be changed once they are created or declared. These types of elements are used only with sensitive data to ensure safety and prevent any changes from unauthorised personnel.
- Immutable data types cannot be changed once they are created.
- They are generally more memory efficient and do not require more memory space.
- These data types are used in situations where data integrity is very much important.
- For example, integers, floats, booleans, strings, tuples, and more.
Let us take an example to understand the Python immutable objects below.
We will take a tuple and try to modify its value at a particular index and print it on the screen. We know tuples are immutable object which will throw an error when we make an attempt to change or modify its elements.
# Create a tuple
my_tuple = (10, 20, 30) # Try to modify an element at index 1 print(“Original Tuple:”, my_tuple) # This will raise a TypeError my_tuple[1] = 99 # Print the modified tuple print(“Modified Tuple:”, my_tuple) |
Output
![]() |
Let us now try to make changes in Python String and try to modify its value. But Strings are immutable and hence will throw an error message when we try to make any changes in it.
text = “hello”
text[0] = “y” |
Output
![]() |
Difference Mutable and Immutable In Python Programming
Mutable and Immutable in Python is an important concept as many of us often get confused whether or not we can make changes in a particular data type in Python. It is important to understand the difference between mutable and immutable in Python programming language.
Mutable Objects | Immutable Objects |
In Python mutable objects are data types or objects whose value can be changed once declared. | In Python immutable objects values cannot be altered or modified once they are created. |
You can easily make modifications without the need to create a completely new object. | You need to create a new object if you want to make new changes in the object. |
Mutable objects are less memory efficient and require more space due to the changes possible. | Immutable objects are more memory efficient as they are not going to have any changes once after creation. |
This entity is super useful where you need dynamic data collection to make frequent changes. | This is useful when you do not want anyone to interfere or make changes. You want to keep the object constant after creation. |
It is slightly slower in performance as compared to Immutable python objects. | It is faster because of the fixed data values inside. |
It can alter the original object when changes are made. | New object must be created to make any significant changes. |
For example, dictionaries, set, lists, bytearray, etc. | For example, int, float, str, tuple, bytes, and more. |
Python Object, Value, Identity and Type
Python consists of everything as an object where numbers, classes, functions, modules, strings all are Python objects. Every character in Python consists of three major attributes.
- Value
- Identity
- Type
The value in Python is the most familiar characteristic in any entity. Let us understand it with the help of simple examples.
x = 42
print(“Value of x:”, x) print(“Identity of x (id):”, id(x)) print(“Type of x:”, type(x)) y = x print(“Value of y:”, y) print(“Identity of y (id):”, id(y)) x = 100 print(“\nAfter changing x:”) print(“Value of x:”, x) print(“Identity of new x:”, id(x)) print(“Value of y:”, y) print(“Identity of y remains:”, id(y)) |
Output
![]() |
We can use the Python built-in method to get the results as an output. Suppose there is a predefined method i,e. len() in Python which will get you the number of items contained in a list object.
x = len([3,4,5])
print (x) |
Output
![]() |
Working with Mutable and Immutable In Python
Mutable and immutable in Python are considered to be two of the most important entities available in Python. The uses of both these entities differ and are completely based on the situation.
When we are working with mutable objects in Python then you have to consider that anyone can make any kind of changes in the object i,e. List, sets, dictionaries, or other entities. When you are working with mutable elements then you will need to allot more memory space to the object. This will lead to many different and related copies of the same information or data available in the context.
Also, using mutable objects with the threads becomes a challenging task. Integrating threads with mutable objects becomes a tedious task as you need synchronization, failure of which will lead to deadlocks.
Now, using immutable objects in Python facilitates providing you with data integrity. If you want to understand a piece of code and track any changes then you will notice that immutable objects cannot mutate any information or value.
Immutable Built in Data Types In Python Programming Language
Python language provides a rich source of immutable built in data types such as number, boolean, and more.
1. Numeric Types
The numerical types of data in Python, such as Integer, float, complex, are some of the numerical data types used in Python which can store multiple values together.
The numbers such as float, int, complex can be used in Python throughout the code. We will create a reference using the assignment operator. Try to change the value of the integer variable.
2. Booleans
Python has built-in types of booleans having two possible values i,e. True or false. These values also take constants such 1 and 0 respectively.
For example, let us take a simple example of boolean built-in data types given below.
a = True
b = False print(“Value of a:”, a) print(“Value of b:”, b) print(“Type of a:”, type(a)) print(“Type of b:”, type(b)) |
Output
![]() |
3. Strings
Python Strings are sequences of individual characters which can be accessed using the indexing operator based on a zero based integer indexing. Let us get an example to understand the immutable strings in Python.
text = “Python”
print(“Original String:”, text) text[0] = “J” |
Output
![]() |
4. Bytes
The built-in data type bytes are immutable types in Python which is used to store binary data in machines or computers. It might look similar to the string because of their syntax.
data = b”Hello”
print(“Original bytes:”, data) print(“Type:”, type(data)) data[0] = 72 |
Output
![]() |
Mutable Built-In Types In Python Programming Language
Let us get some information about some built-in mutable data types in Python programming.
1. List
List is an ordered collection of elements which can easily be added, deleted, or modified as per the needs of the users.
my_list = [1, 2, 3]
my_list[0] = 100 |
Output
![]() |
2. Dictionary
The Dictionary consists of keys and value pairs which can be used to store values in data. Let us check a simple example below.
my_dict = {“name”: “Alice”}
my_dict[“name”] = “Bob” |
Output
![]() |
As you can see the name is changed from “Alice” to “Bob” easily as dictionaries are mutable types in Python.
Learn Data Science With Benefit of Generative AI
Harness the power of artificial intelligence with PW Skills Data Science Course. This course provides an in-depth tutorial with all tools and technologies offered by dedicated mentors.
Work on real world projects, practice exercises, module assignments, and more. Complete all assessments and quizzes to get certification after completing the entire course. Build a strong portfolio and discover a wide range of career opportunities in Data Science.
Mutable and Immutable In Python Programming FAQs
Q1. What are immutable and mutable in Python?
Ans: In Python immutable elements, data types, or objects cannot be changed or modified once declared. While, mutable elements can be modified or altered even after creation.
Q2. What are some example of immutable objects in Python?
Ans: Strings, tuple, int, float, bytes are some of the Python data types which cannot be altered after creation.
Q3. What are some examples of Mutable objects in Python?
Ans: Some examples of Mutable objects in Python programming are list, dictionary, set, bytearray, and more.
Q4. Is tuple immutable in Python programming?
Ans: In Python programming, tuples are immutable and cannot be changed once they are created.