Difference Between Mutable and Immutable in Python With Examples
Updated on Jan 28, 2025 | 12 min read | 1.7k views
Share:
For working professionals
For fresh graduates
More
Updated on Jan 28, 2025 | 12 min read | 1.7k views
Share:
Table of Contents
Python, known for its simplicity and flexibility, offers a wide variety of data types that form the backbone of any Python program. These include integers, floats, strings, lists, dictionaries, and tuples.
Python’s data types are categorized into two main groups: mutable and immutable. Mutable objects, like lists and dictionaries, allow you to modify their content after creation, while immutable objects, such as strings and tuples, cannot be altered once they’re defined.
In this blog, we’ll look at the key differences and similarities between mutable and immutable objects, helping you understand their behavior better and make better coding decisions. This understanding impacts everything from memory management to performance and how data is passed around in your program, playing a crucial role in understanding how Python works.
Level Up for FREE: Explore Top Python Tutorials Now!
In Python, mutable objects are data types that can be modified after they are created. This means that once a mutable object is instantiated, its content can be altered without creating a new object. This ability to change the object’s state makes mutable types flexible and ideal for scenarios where you need to modify data frequently.
Some common examples of mutable data types in Python include:
A list is an ordered collection of items in Python. The items can be of any data type (integers, strings, or even other lists). Lists are one of the most commonly used data structures in Python because they allow you to store multiple values in a single variable.
Get in-depth insights on Lists with this detailed List in Python Tutorial
# Create a list with three numbers
my_list = [1, 2, 3]
# Add an item to the list
my_list.append(4) # This modifies the original list
# Change an existing item in the list
my_list[0] = 10 # Changing the first element from 1 to 10
# Remove an item from the list
my_list.remove(3) # This removes the item with the value 3
print(my_list)
Output: [10, 2, 4]
A dictionary in Python is a collection of key-value pairs. Each item in a dictionary has a key (which is unique) and an associated value. Dictionaries are extremely useful when you want to store data that has a relationship, like a person's name and age.
Click here to read more about Top 7 Data Types of Python | Python Data Types
# Create a dictionary with key-value pairs
my_dict = {"name": "Alice", "age": 25}
# Modify an existing value
my_dict["age"] = 26 # Change the age from 25 to 26
# Add a new key-value pair
my_dict["city"] = "New York" # Adding a new pair
# Remove a key-value pair
del my_dict["name"] # Remove the key 'name'
print(my_dict)
Output: {'age': 26, 'city': 'New York'}
Learn more about dictionaries in Python with this free Dictionary in Python Tutorial
A set is an unordered collection of unique items. Unlike lists and dictionaries, sets don’t allow duplicate elements. Sets are useful when you need to store a collection of items without caring about the order or the presence of duplicates.
# Create a set with some numbers
my_set = {1, 2, 3}
# Add an item to the set
my_set.add(4) # Adding a new element
# Remove an item from the set
my_set.remove(2) # Removes the number 2 from the set
# Try adding a duplicate (won't change the set)
my_set.add(3) # 3 is already in the set, so it won't be added again
print(my_set)
Output: {1, 3, 4}
Improve your Python knowledge with this detailed Set in Python Tutorial
Mutable objects in Python share a few key characteristics:
Level Up Your Skills. Explore Top Python Tutorials Now!
Example:
Code:
# Example 1: Mutable Object - List
my_list = [1, 2, 3]
print("Original List:", my_list)
# Modifying the list
my_list.append(4)
print("Modified List:", my_list)
# Example 2: Mutable Object - Dictionary
my_dict = {"name": "Alice", "age": 25}
print("Original Dictionary:", my_dict)
# Modifying the dictionary
my_dict["age"] = 26
my_dict["city"] = "New York"
print("Modified Dictionary:", my_dict)
# Example of passing mutable object to a function
def modify_list(lst):
lst[0] = 100 # Modifies the original list
lst.append(200) # Appends a new value
print("Before Function Call:", my_list)
modify_list(my_list)
print("After Function Call:", my_list)
Output:
Original List: [1, 2, 3]
Modified List: [1, 2, 3, 4]
Original Dictionary: {'name': 'Alice', 'age': 25}
Modified Dictionary: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Before Function Call: [1, 2, 3, 4]
After Function Call: [100, 2, 3, 4, 200]
Explanation:
Take this Free Programming with Python Course and get started with Python programming, covering control statements, basic data structures, and OOP concepts.
In Python, an immutable object is a data type whose state cannot be changed once it is created. Unlike mutable objects, you cannot modify, add, or remove elements from an immutable object after it has been initialized. This immutability ensures that the object remains constant throughout its lifetime.
When you attempt to modify an immutable object, Python creates a new object with the updated content, leaving the original object unchanged. This behavior makes immutable objects ideal for situations where consistency and safety are crucial, such as when working with data that should not be modified.
Some common immutable data types in Python include:
Must Read: Arrays in Python: What are Arrays in Python & How to Use Them?
Immutable objects in Python have several distinct characteristics:
Code:
# Example 1: String (Immutable)
my_string = "Hello"
# You can't change a specific character in the string
# my_string[0] = "h" # This will raise an error
new_string = my_string + " World" # A new string is created
print(new_string) # Output: "Hello World"
# Example 2: Tuple (Immutable)
my_tuple = (1, 2, 3)
# You can't change an element in the tuple
# my_tuple[0] = 100 # This will raise an error
new_tuple = my_tuple + (4,) # A new tuple is created
print(new_tuple) # Output: (1, 2, 3, 4)
# Example 3: Integer (Immutable)
x = 5
# You can't change the integer itself
# x[0] = 10 # This will raise an error
y = x + 5 # A new integer object is created
print(y)
Output:
Hello World
(1, 2, 3, 4)
10
Also Read: Why Learn Python – Top 10 Reasons to Learn Python
Get ready to learn from the best. Earn a Post Graduate Certificate in Machine Learning & NLP from IIIT-B
In Python, mutable objects (like lists and dictionaries) can be changed after creation, while immutable objects (such as strings and tuples) cannot. Understanding these differences is crucial for efficient memory management, performance, and thread safety. Below is a comparison of the key distinctions between mutable and immutable objects in Python.
Attribute |
Mutable |
Immutable |
Modification Behavior | Can be updated in-place (e.g., adding, removing, or changing elements). | Modifications require creating a new object (e.g., concatenating strings or changing tuple values). |
Memory Management | Retain the same memory location even after modification. | Create a new memory location when modified. |
Hashability | Not hashable; cannot be used as dictionary keys or in sets. | Hashable; can be used as dictionary keys or in sets (e.g., strings, integers, tuples). |
Object Identity | Keep their identity even after modification (e.g., reference to the same object remains). | Don’t retain the same identity after modification (a new object is created). |
Thread Safety | Not thread-safe by default; modifications in one thread can affect other threads. | Thread-safe; since they cannot be modified, they are safe in multi-threaded environments. |
Performance | Faster for frequent updates or changes due to in-place modification. | Better for scenarios with frequent reads, but slower for modifications as new objects are created. |
Use in Functional Programming | Not ideal; functional programming prefers immutability. | Align better with functional programming principles, where immutability ensures no side effects. |
Storage in Collections | Cannot be used in sets or as dictionary keys (e.g., lists, dictionaries). | Can be stored in sets or used as dictionary keys (e.g., strings, integers, and tuples). |
Practical Applications | Useful for dynamic data structures where changes are frequent (e.g., lists, dictionaries). | Ideal for constants, configuration values, or objects that shouldn't change (e.g., strings, tuples, integers). |
Click Here to Learn More: Essential Skills and a Step-by-Step Guide to Becoming a Python Developer
While mutable and immutable objects have distinct characteristics, they also share a number of core similarities. Understanding these commonalities is important for gaining a deeper insight into how Python handles data types. Despite differences in their ability to change, both types of objects provide foundational functionalities and integrate seamlessly into Python's object-oriented system.
In Python, the choice between mutable and immutable objects plays a crucial role in how your code behaves and performs. Mutable objects, like lists and dictionaries, offer flexibility, allowing for in-place changes, which is useful for dynamic data manipulation. On the other hand, immutable objects, such as strings and tuples, provide a layer of safety by ensuring that their values cannot be altered, making them ideal for scenarios requiring consistency and reliability.
The key takeaway is that understanding the strengths and limitations of each type of these objects helps you write and execute a good and functional code. By selecting the right object type based on the specific requirements of your program, you can ensure efficient and bug-free Python development.
upGrad’s Machine Learning courses comprehensively cover foundational to advanced topics, equipping you with the expertise to design, deploy, and optimize ML models and thrive in the dynamic AI landscape.
Not sure where to start? upGrad is here to help you with insights from experts. Click on the link to book a free counseling session.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources