🎯 Understanding Mutable and Immutable Objects in Python

Hey 👋🏻, I am , a Software Engineer from India. I am interested in, write about, and develop (open source) software solutions for and with JavaScript, ReactJs. 📬 Get in touch
Twitter: https://x.com/SankalpHaritash Blog: https://sankalp-haritash.hashnode.dev/ LinkedIn: https://www.linkedin.com/in/sankalp-haritash/ GitHub: https://github.com/SankalpHaritash21
📧 Sign up for my newsletter: https://sankalp-haritash.hashnode.dev/newsletter
When I started with Python, one of the most important thing to understand is the difference between mutable and immutable objects. I keep on wondered why some objects can be modified while others can’t, Here I combined all my doubts! 🚀

What Are Mutable and Immutable Objects?
Mutable Objects: Can be modified after they are created.
Immutable Objects: Cannot be modified after they are created. Any change creates a new object.
Mutable Objects – Can Be Changed
In Mutable objects we can changes content without creating a new object. It means we can modify our content without creating new object
Examples of Mutable Objects:
Lists
Dictionaries
Sets
User-defined objects (by default)
Example: Lists are Mutable
# Create a list
my_list = [1, 2, 3]
print("Original List:", my_list)
# Modify the list by changing an element
my_list[1] = 100
print("Modified List:", my_list)
👉 Output:
Original List: [1, 2, 3]
Modified List: [1, 100, 3]
Here, the list was modified without creating a new object. The same list is updated.
Adding or Removing Elements in a List
# Add a new element
my_list.append(4)
print("List after adding an element:", my_list)
# Remove an element
my_list.remove(100)
print("List after removing an element:", my_list)
👉 Output:
List after adding an element: [1, 100, 3, 4]
List after removing an element: [1, 3, 4]
➡️ Dictionaries are Also Mutable
# Create a dictionary
my_dict = {"name": "John", "age": 25}
# Modify a value
my_dict["age"] = 30
print("Modified Dictionary:", my_dict)
# Add a new key-value pair
my_dict["city"] = "New York"
print("Updated Dictionary:", my_dict)
👉 Output:
Modified Dictionary: {'name': 'John', 'age': 30}
Updated Dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}
As you can see, dictionaries can be modified by changing values or adding new key-value pairs.
🔴 2. Immutable Objects – Cannot Be Changed
Immutable objects, on the other hand, cannot be changed once they are created. Any modification to an immutable object creates a new object in memory.
✅ Examples of Immutable Objects:
Strings
Tuples
Integers
Floats
Booleans
➡️ Example: Strings are Immutable
# Create a string
my_string = "Hello"
print("Original String:", my_string)
# Modify the string
my_string += " World"
print("Modified String:", my_string)
👉 Output:
Original String: Hello
Modified String: Hello World
Even though we added “World” to the string, Python created a new string instead of modifying the original one. The original string "Hello" is unchanged.
➡️ Tuples are Also Immutable
# Create a tuple
my_tuple = (1, 2, 3)
print("Original Tuple:", my_tuple)
# Try modifying the tuple (this will cause an error)
# my_tuple[1] = 100 # ❌ This will throw TypeError
If you try to change the tuple, Python will raise a TypeError because tuples cannot be modified.
➡️ Integers and Floats are Immutable
# Create an integer
my_num = 10
print("Original Number:", my_num)
# Modify the number
my_num += 5
print("Modified Number:", my_num)
👉 Output:
Original Number: 10
Modified Number: 15
Again, when we modified my_num, Python created a new object and assigned the modified value to the variable.
🎯 3. Key Differences Between Mutable and Immutable Objects
Here’s a quick comparison to summarize the differences:
| Feature | Mutable | Immutable |
| Definition | Can be modified | Cannot be modified |
| Memory Address | Same after modification | Different after modification |
| Examples | Lists, Dicts, Sets | Strings, Tuples, Integers |
| Modifiability | Yes, content can change | No, new object created |
| Hashability | Not hashable | Hashable (can be used as keys) |
⚡️ 4. Checking Memory Addresses Using id()
To prove whether an object is mutable or immutable, we can use the id() function to check the memory address before and after modification.
➡️ Checking with a List (Mutable)
my_list = [1, 2, 3]
print("ID before modification:", id(my_list))
# Modify the list
my_list.append(4)
print("ID after modification:", id(my_list)) # Same ID
👉 Output:
ID before modification: 140362018402944
ID after modification: 140362018402944
The memory address remains the same because lists are mutable.
➡️ Checking with a String (Immutable)
my_string = "Hello"
print("ID before modification:", id(my_string))
# Modify the string
my_string += " World"
print("ID after modification:", id(my_string)) # New ID
👉 Output:
ID before modification: 140362017543920
ID after modification: 140362017864832
The memory address changes because strings are immutable and a new object is created.
🔥 5. Complex Example with Mutable and Immutable Objects
Let’s create a user profile management system to demonstrate these concepts:
# User profile data
user_id = 101 # Immutable (Integer)
username = "sankalp22" # Immutable (String)
preferences = {"theme": "dark", "notifications": True} # Mutable (Dictionary)
purchase_history = ["Book", "Laptop"] # Mutable (List)
location = (28.6139, 77.2090) # Immutable (Tuple)
# Modify mutable objects
preferences["theme"] = "light" # Modify dictionary
purchase_history.append("Smartphone") # Add to list
print("Updated Preferences:", preferences)
print("Updated Purchase History:", purchase_history)
# Attempt to modify immutable objects
username += "_updated"
print("Updated Username:", username) # Creates a new string
# Using tuple as a key in a dictionary
location_data = {location: "New Delhi, India"}
print("Location Data:", location_data[location])
👉 Output:
Updated Preferences: {'theme': 'light', 'notifications': True}
Updated Purchase History: ['Book', 'Laptop', 'Smartphone']
Updated Username: sankalp22_updated
Location Data: New Delhi, India
Why Does This Matter?
Understanding mutability and immutability is important because:
It affects how data is stored and modified.
It helps in avoiding unexpected behavior in Python programs.
It ensures safe handling of data when passing objects between functions.
When to Use What?
✅ Use Mutable Objects When:
We need to modify or update data frequently.
Suitable for dynamic data that changes over time.
✅ Use Immutable Objects When:
You want to ensure that data remains constant.
Useful for keys in dictionaries or elements in sets.
Summary
Strings, Tuples, and Integers are immutable.
Lists, Dictionaries, and Sets are mutable.
Always check the memory address with
id()to confirm mutability.
Happy Coding! 🎯




