View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Difference Between Mutable and Immutable in Python With Examples

By Rohit Sharma

Updated on Jan 28, 2025 | 12 min read | 1.7k views

Share:

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!

Python Tutorial

What Is Mutable Data Type in Python?

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:

  • Lists

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.

Key Features of Lists:

  • Ordered: The order in which you add items to a list is preserved. The first item will always be at index 0, the second at index 1, and so on.
  • Mutable: You can change the contents of a list after it's created by adding, removing, or modifying elements.

Get in-depth insights on Lists with this detailed List in Python Tutorial

Example of List Modification:

# 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]

Enroll in a Free Basic Python Programming Course and enhance your Python problem-solving skills through coding questions on lists, strings, and data structures like tuples, sets, and dictionaries.

  • Dictionaries

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.

Key Features of Dictionaries:

  • Unordered: The order of key-value pairs in a dictionary is not guaranteed (Python 3.7+ maintains insertion order, but it's not meant to be used for order-dependent tasks).
  • Mutable: You can change, add, or remove key-value pairs after the dictionary is created.

Click here to read more about Top 7 Data Types of Python | Python Data Types

Example of Dictionary Modification:

# 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

  • Sets

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.

Key Features of Sets:

  • Unordered: The items in a set have no specific order, and you cannot access them by index.
  • Mutable: You can add or remove elements from a set, but you cannot change individual elements (since there’s no index or order).

Example of Set Modification:

# 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

Characteristics and Behavior of Mutable Objects

 Mutable objects in Python share a few key characteristics:

  • In-place Modification: Their contents can be changed directly. For example, you can append an item to a list or update a value in a dictionary without creating a new object.
  • Memory Address: Since mutable objects can be modified, they maintain the same memory address throughout their lifetime, even when their contents change.
  • Impact on References: When a mutable object is passed as an argument to a function or assigned to another variable, changes made to the object will affect all references to it.

Level Up Your Skills. Explore Top Python Tutorials Now!

Data Types in Python Tutorial

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:

  1. List Example:
    The list my_list starts with the elements [1, 2, 3]. We modify the list by appending the value 4, which updates the original list.
  2. Dictionary Example:
    The dictionary my_dict starts with {"name": "Alice", "age": 25}. We then update the value of "age" and add a new key-value pair for "city", showing that dictionaries are mutable too.
  3. Passing a Mutable Object to a Function:
    We define a function modify_list that modifies the passed list. Since lists are mutable, the changes made inside the function affect the original list (my_list).

 

Take this Free Programming with Python Course and get started with Python programming, covering control statements, basic data structures, and OOP concepts.

 

What Is Immutable Data Type in Python?

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.

Examples of Immutable Data Types

Some common immutable data types in Python include:

  • Strings: Sequences of characters that cannot be altered once created.
  • Tuples: Ordered collections of items, similar to lists, but immutable.
  • Integers: Whole numbers that cannot be changed after they are created.
  • Floats: Decimal numbers that, like integers, cannot be modified after creation.

Must Read: Arrays in Python: What are Arrays in Python & How to Use Them?

Characteristics and Behavior of Immutable Objects

Immutable objects in Python have several distinct characteristics:

  • Inability to Modify: Once an immutable object is created, you cannot change its contents. For example, you cannot modify an individual character in a string or change an element in a tuple.
  • Creation of New Objects: When you attempt to alter an immutable object, Python creates a new object rather than modifying the original. For instance, concatenating strings or changing a tuple’s elements results in the creation of a completely new string or tuple.
  • Efficiency in Memory and Performance: Since immutable objects cannot change, they are more memory-efficient in certain situations, as Python can optimize their storage and reuse them across multiple parts of the program.
  • Hashable: Many immutable objects in Python (like strings, tuples, and integers) are hashable, which means they can be used as keys in dictionaries or added to sets. This property is not available to mutable objects.
  • Safety in Multi-threading: Immutable objects are safe to use in multi-threaded environments because their contents cannot be changed by different threads, ensuring that no race conditions occur when accessing them.

Example of Immutable Objects:

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

Explanation of Output:

  • String Example:
    The original string my_string is "Hello". When you try to concatenate " World", a new string "Hello World" is created. The original string my_string remains unchanged.
  • Tuple Example:
    The tuple my_tuple is (1, 2, 3). When you add (4,) to it, a new tuple (1, 2, 3, 4) is created. The original tuple my_tuple is unchanged.
  • Integer Example:
    The integer x is 5. When you add 5 to it, a new integer 10 is created. The original integer x remains unchanged.

 

Get ready to learn from the best. Earn a Post Graduate Certificate in Machine Learning & NLP  from IIIT-B

 

Key Differences Between Mutable and Immutable in Python

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

Similarities Between Mutable and Immutable in Python

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.

  • Both Are Objects in Python: Both mutable and immutable types are objects in Python, derived from the base object class. This means they follow the same core principles of Python's object-oriented nature, such as inheritance, methods, and attributes.
  • Both Can Be Assigned to Variables: Both mutable and immutable objects can be assigned to variables, stored in data structures, and passed as arguments to functions. This flexibility allows developers to work with both types interchangeably in most contexts.
  • Support for Methods and Attributes: Both mutable and immutable objects support methods and can have attributes. However, while mutable objects can modify their internal state, immutable objects create new objects when attempting changes, preserving their original state.
  • Memory Management by Python’s Internal System: Python's memory management system, using reference counting and garbage collection, applies to both mutable and immutable objects. This ensures efficient memory usage and automatic cleanup when objects are no longer in use.
  • Behavior in Collections: Both types of objects can be included in collections such as lists, tuples, and dictionaries. The key difference is that only immutable objects can be used as dictionary keys or stored in sets, due to their hashability.
  • Implementation of Polymorphism: Both mutable and immutable objects can implement polymorphism, allowing them to inherit from other classes and be used in various ways with Python’s operators, functions, or methods, making them adaptable in different scenarios.

Enroll yourself in a Job-ready Program in Artificial Intelligence & Machine Learning from upGrad and gain practical experience with Python Toolkit, SQL, and Large Language Models such as ChatGPT through this comprehensive Artificial Intelligence and Machine Learning Program.

Conclusion

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.

 

Similar Reads:

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.

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree18 Months
View Program

Placement Assistance

Certification8-8.5 Months
View Program

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!

Frequently Asked Questions (FAQs)

1. Why does Python have both mutable and immutable data types?

2. Can an immutable object ever change in Python?

3. How do I check if an object is mutable or immutable in Python?

4. Why are immutable objects hashable?

5. What are some real-world applications of mutable objects?

6. Do immutable objects consume less memory than mutable objects?

7. How does Python manage memory for mutable and immutable objects?

8. Are custom classes mutable or immutable by default in Python?

9. What are the performance considerations when using immutable objects?

10. Can mutable and immutable objects coexist in the same data structure?

11. How does immutability help in multithreading?

Rohit Sharma

694 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

View Program
Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

18 Months

View Program
upGrad Logo

Certification

3 Months

View Program