Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Mutable and Immutable in Python – Key Differences

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

In Python, objects can be classified into two categories: mutable and immutable. In simple terms, mutable objects can be changed after they are created, while immutable objects cannot be altered. Everything is an object with a unique ID assigned upon creation. The type of an object is fixed, but its value can be modified if the object is mutable.

 

For example, a list remains a list, but its elements can be changed. Understanding the difference between mutable and immutable objects is key to managing data effectively and writing robust Python code. In this article, we will understand the difference between the mutable and immutable, with examples for better understanding.

What is a Mutable Object in Python?

In simple terms, a mutable object in Python is something that can be changed after it is created. This means you can modify, add, or remove elements within the object without creating a new object. Lists, dictionaries, and sets are examples of mutable objects.

Example 1: List

A list is a collection of items that can be changed after it is created. You can add, remove, or modify elements in a list.

#Creation of a List first = [1, 2, 3] # Modifying the list first.append(4)    # Adding an element in the List first.[0] = 10          # Changing an element in the List print(first)

Output

[10, 2, 3, 4]

Example 2:  Set

A set is an unordered collection of unique elements. You can add or remove elements in a set.

# Creation of  a set first = {1, 2, 3} # Modifying the set first.add(4)        # Adding an element in set first.remove(2)  # Removing an element in set print(first)

Output

{1, 3, 4}

Example 3:  Dictionary

A dictionary is a collection of key-value pairs. You can add, remove, or modify key-value pairs in a dictionary.

# Creation of  a dictionary first = {'a': 1, 'b': 2} # Modifying the dictionary first['c'] = 3       # Adding a new key-value pair in dictionary first['a'] = 10     # Changing the value of an existing key in the dictionary del first['b']       # Removing a key-value pair in the dictionary print(first)

Output

{'a': 10, 'c': 3}

What is an Immutable Object in Python?

An immutable object in Python is one that cannot be changed once it is created. This means that after you create an immutable object, its content or state remains constant. Common examples of immutable objects are numbers, strings, and tuples.

Example 1: Numbers

Numbers, such as integers and floats, are immutable. Once a number is created, it cannot be changed.

# Creating a number first = 5                   # Changing the number creates a new object first = first + 1 print(first)

Output

6

Example 2: Strings

Strings are sequences of characters and are immutable. Any modification to a string creates a new string.

# Creation of a string first = "Hello"    # Changing the string creates a new object second = first + " World" print(second) print(first)

Output

Hello World Hello

Example 3: Tuples

Tuples are ordered collections of elements and are immutable. Once a tuple is created, its elements cannot be changed.

# Creation of  a tuple first = (1, 2, 3) first[0] = 10      #this line will raise a TypeError # Creation of  a new tuple with modified elements second = first + (4,) print(first) print(second)

Output

Error
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Difference Between Mutable and Immutable Objects

Features Mutable Objects Immutable Objects
Definition Can be modified after they are created Cannot be modified after they are created
Modification Behaviour Changes affect the original object directly Any change creates a new object with the modified value
Variable References Multiple variables can refer to the same mutable object, leading to unexpected changes Immutable objects are thread-safe and can be shared between threads without the risk of unexpected changes
Use Cases Ideal for dynamic data structures needing frequent updates, like lists or dictionaries Suitable as dictionary keys or set elements since their values remain constant and always have the same hash value
Performance Modifying a mutable object can be quicker and use less memory than creating a new object, especially for large data structures Often used for constants or values that should not change, like numeric values or strings used for formatting messages

Conclusion

In this article, we learned the difference between mutable and immutable objects in Python. Understanding the mutable and immutable objects helps you modify the programme according to the requirements and makes the writing efficient and predictable.

 

Mutable objects, like lists and dictionaries, can be changed after creation, making them ideal for dynamic data. However, they can cause unintended consequences if multiple variables reference the same object. Immutable objects, like numbers and strings, cannot be altered once created, ensuring thread safety and suitability for dictionary keys and set elements. Recognising when to use each type improves the performance, reliability, and clarity of your Python programmes.

FAQs
In Python, Mutable objects can be changed after they are created. This means mutable objects can modify, add or remove elements within the object without creating a new object. Some examples of mutable objects are lists, dictionaries and sets.
In Python, Immutable objects cannot be changed once they are created. Any operation that appears to change an immutable object actually creates a new object with the modified value. Numbers, strings, and tuples are examples of immutable objects.
Immutable objects are useful because they ensure data integrity and thread safety. Once created, their values cannot be altered, which makes them suitable for use as dictionary keys, elements in sets, or when you need to guarantee that the data will not change unexpectedly.
Mutable objects allow for efficient modification of data structures, especially when dealing with large datasets. They can be faster and more memory-efficient than creating new objects, as changes are made directly to the existing object.
Mutable objects, such as lists and dictionaries, can be more performant when frequent modifications are required, as they avoid the overhead of creating new objects. Immutable objects, on the other hand, ensure predictable behaviour and are often used for constants or data that should remain unchanged.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved