Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Mutable and Immutable in Python

Last Updated on November 27, 2023 by Ankit Kochar

Python, as a versatile programming language, employs various data types to store and manipulate information. Among these types are mutable and immutable objects, which play a crucial role in understanding Python’s behavior in terms of memory management, data manipulation, and programming paradigms. Understanding the distinction between mutable and immutable objects is fundamental for Python developers to write efficient, bug-free, and optimized code. This article aims to delve into the concept of mutable and immutable objects in Python, elucidating their differences, usage scenarios, and implications in programming.

What are Mutable and Immutable Objects?

A mutable object is an object whose value can be changed after it is created. In other words, the internal state of the object can be modified without creating a new object.

Examples of mutable objects in Python include,

  • Lists
  • Dictionaries
  • Sets

On the other hand, an immutable object is an object whose value cannot be changed once it is created. Any operation that appears to modify an immutable object actually creates a new object with the modified value.

Examples of immutable objects in Python include,

  • Strings
  • Numbers
  • Tuples

Now let us study these Mutable and Immutable Objects in Python in detail.

Mutable Objects in Python

As mentioned earlier, mutable objects are those whose value can be changed after creation. This means that any changes made to the object will modify the object itself, without creating a new object.

Lists

Lists are a commonly used mutable object in Python. A list can be modified by adding, removing, or changing elements. The following code demonstrates the mutability of lists in Python.

Code:

list = [1, 2, 3]
print("Original List: ", list)


# adding element
list.append(4)
print("List after adding element: ", list)


# modifying element
list[0] = 5
print("List after modifying element: ", list)


# removing element
list.remove(5)
print("List after removing an element: ", list)

Output:

Original List:  [1, 2, 3]
List after adding element:  [1, 2, 3, 4]
List after modifying element:  [5, 2, 3, 4]
List after removing an element:  [2, 3, 4]

Explanation:
From the above code, we can easily see that we can add an element, modify any current element, and can also remove the element from the list. This proves that the lists are mutable in Python.

Dictionaries

Dictionaries are another commonly used mutable object in Python and are used to store key-value pairs. A dictionary can be modified by adding, removing, or changing key-value pairs. This can be seen in the code given below.

Code:

dict = {'a': 1, 'b': 2}
print("Original Dictionary: ", dict)


# Adding a key value paper
dict['c'] = 3
print("Dictionary after adding key-value pair: ", dict)


# modifying a value
dict['a'] = 4
print("Dictionary after modifying a value: ", dict)


# removing key value pair
del dict['b']
print("Dictionary after removing element: ", dict)

Output:

Original Dictionary:  {'a': 1, 'b': 2}
Dictionary after adding key-value pair:  {'a': 1, 'b': 2, 'c': 3}
Dictionary after modifying a value:  {'a': 4, 'b': 2, 'c': 3}
Dictionary after removing element:  {'a': 4, 'c': 3}

Explanation:
From the above example, it is clear that we can add key-value pairs, modify values, and remove key-value pairs from a dictionary, all of which modify the dictionary itself. Thus, a Dictionary is a Mutable Object in Python.

Sets

Sets are another mutable object in Python that can be modified by adding or removing elements. Here’s an example.

Code:

set = {1, 2, 3}
print("Original set: ", set)


# Adding element in set
set.add(4)
print("Set after adding element: ", set)


# Removing element
set.remove(3)
print("Set after removing element: ", set)

Output:

Original set:  {1, 2, 3}
Set after adding element:  {1, 2, 3, 4}
Set after removing element:  {1, 2, 4}

Explanation:
In the above code, we get no error when we try to add or remove an element from the set which proves that a set is a mutable object in Python.

Immutable Objects in Python

As mentioned earlier, immutable objects are those whose value cannot be changed once they are created. This means that any operation that appears to modify an immutable object actually creates a new object with the modified value.

Strings

Strings are a commonly used immutable object in Python. A string can be indexed and sliced, but any attempt to modify a string will result in the creation of a new string object. This statement will be more clear by the following code.

Code:

str = "PrepBytes"


# This will result in creation of new object
str += "CollegeDekho"
print(str)

Output:

PrepBytesCollegeDekho

Explanation:
As we can see if we try to concatenate a string. It does not modify the original string. Instead, it creates a new string object by concatenating the original string with the new string.

Moreover, we cannot modify a particular character from a string. The given code shows what happens if we try to modify a character in the string.

Code:

str = "PrepBytes"
str[1] = 'a'

Output:

Traceback (most recent call last):
  File "a.py", line 2, in 
    str[1] = 'a'
TypeError: 'str' object does not support item assignment

Explanation:
As we can see, attempting to modify a string will result in a TypeError. Thus, strings are Immutable in Python.

Numbers

Numbers in Python are also immutable. This means that any attempt to modify a number will result in the creation of a new number object as shown in the code given below.

Code:

n = 5


# The value will not change in place
# in fact, a new number object is created
n += 2
print(n)

Output:

7

Explanation:
Here, in this code, the value of n was not modified in place, but a new number object was created with the new value.

Tuples

Tuples are another example of an immutable object in Python. The values of tuples cannot be changed, after their creation. Here’s an example.

Code:

tup = (1, 2, 3)


# This will raise an error because tuples are immutable
tup[1] = 6

Output:

Traceback (most recent call last):
  File "a.py", line 4, in 
    tup[1] = 6
TypeError: 'tuple' object does not support item assignment

Explanation:
As we can see, attempting to modify a tuple will result in a TypeError.

For detailed knowledge of the topic, read the following article – Is Tuple Mutable or Immutable in Python?

Conclusion
In conclusion, the differentiation between mutable and immutable objects is a pivotal aspect of Python programming. The distinction influences how data is manipulated, stored, and accessed within Python code. Mutable objects allow changes to their internal state, while immutable objects, once created, remain unchangeable. Recognizing when to use mutable or immutable objects is crucial in writing efficient and robust code. While mutable objects offer flexibility and the ability to modify data in place, immutable objects provide advantages in terms of safety, caching, and thread safety.

Understanding the nuances between these two types is essential for Python developers to design programs that are efficient, maintainable, and less prone to bugs. By leveraging the properties of mutable and immutable objects, developers can optimize memory usage, improve code readability, and ensure better overall performance in their Python applications.

Frequently Asked Questions(FAQs) Related to Mutable and Immutable in Python

Here are some Frequently Asked Questions related to “Mutable and Immutable in Python”.

1. What are mutable and immutable objects in Python?
Mutable objects in Python are those whose state or content can be altered after creation. Lists, dictionaries, and sets are examples of mutable objects. On the other hand, immutable objects cannot be changed once created. Examples include tuples, strings, and numbers (integers, floats).

2. What are the advantages of using immutable objects?
Immutable objects offer benefits such as thread safety, as they cannot be modified concurrently, and are thus inherently safe in multithreaded environments. They also enable caching, as their values can be reused without the risk of alteration, leading to potential performance improvements.

3. Why should I use mutable objects?
Mutable objects allow in-place modifications, which can be more memory-efficient and time-saving in certain scenarios. They are beneficial when the data needs frequent alterations without creating new objects, especially in tasks involving large datasets or real-time updates.

4. How do I choose between mutable and immutable objects in my Python code?
Consider the requirements of your program. If the data needs to be frequently changed or updated, mutable objects might be preferable. Conversely, if data integrity and avoiding accidental modifications are crucial, immutable objects are more suitable.

5. Can immutable objects be modified indirectly?
While immutable objects themselves cannot be altered, operations involving immutable objects might create new objects. For instance, concatenating strings or performing arithmetic operations on immutable objects generates new objects rather than modifying the existing ones.

Leave a Reply

Your email address will not be published. Required fields are marked *