Difference Between Mutable and Non Mutable Data Structures
Published by
sanya sanya
Mutable
A mutable data structure would be like a whiteboard where you can easily erase and modify the content on it. You can write new information, change existing information, or even completely erase everything and start over. An example of a mutable data structure is a list in Python:
In this example, we created a list of fruits, and then we added a new fruit to the list using the '.append()' method. The original list was modified, and the new list contains the added element.
fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits) # Output: ["apple", "banana", "cherry", "orange"]
Examples of mutable data structures
1. Lists:
# Create a list fruits = ['apple', 'banana', 'cherry'] # Modify the list fruits.append('orange') fruits[1] = 'pear' # Print the modified list print(fruits) # Output: ['apple', 'pear', 'cherry', 'orange']
In this example, we create a list of fruits and then modify it by appending a new fruit ('orange') and changing the second fruit from 'banana' to 'pear'.
2. Dictionaries:
# Create a dictionary person = {'name': 'Alice', 'age': 30, 'city': 'New York'} # Modify the dictionary person['age'] = 31 person['country'] = 'USA' # Print the modified dictionary print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'country': 'USA'}
In this example, we create a dictionary of person details and then modify it by changing the value of the 'age' key and adding a new key-value pair for 'country'.
3. Sets
# Create a set fruits = {'apple', 'banana', 'cherry'} # Modify the set fruits.add('orange') fruits.remove('banana') # Print the modified set print(fruits) # Output: {'apple', 'cherry', 'orange'}
In this example, we create a set of fruits and then modify it by adding a new fruit ('orange') and removing the fruit 'banana'.
Immutable
On the other hand, a non-mutable data structure would be like a printed book. Once the information is printed, it cannot be changed. You can add new information by writing on a separate piece of paper and attaching it to the book, but the original content remains unchanged. An example of a non-mutable data structure is a tuple in Python:
numbers = (1, 2, 3) # numbers[0] = 4 # Error: Tuples are immutable
In this example, we created a tuple of numbers. We tried to change the first element of the tuple to 4, but we received an error because tuples are immutable and cannot be modified.
In summary, the main difference between mutable and non-mutable data structures is their ability to be modified after they are created. Mutable data structures can be changed, while non-mutable data structures cannot be changed.
Examples of immutable data structures
1. Tuples:
# Create a tuple point = (3, 4) # Try to modify the tuple point[0] = 5 # Raises a TypeError since tuples are immutable
Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14404\2554938485.py in
3
4 # Try to modify the string
----> 5 point[0] = 5 # Raises a TypeError since tuples are immutable
TypeError: 'tuple' object does not support item assignment
In this example, we create a tuple representing a point in a graph and then try to modify its x-coordinate. However, this raises a TypeError since tuples are immutable.
3. Integer and Floats
# Create an integer and a float x = 3 y = 3.5 # Print the value and memory location of x and y print("Before modification: x =", x, "id(x) =", id(x)) print("Before modification: y =", y, "id(y) =", id(y)) # Try to modify the integer and float x = 5 # Assigns a new value to x rather than modifying its existing value y = 4.2 # Assigns a new value to y rather than modifying its existing value # Print the value and memory location of x and y after modifications print("After modification: x =", x, "id(x) =", id(x)) print("After modification: y =", y, "id(y) =", id(y))
Output
Before modification: x = 3 id(x) = 2753072425328
Before modification: y = 3.5 id(y) = 2751009745424
After modification: x = 5 id(x) = 2753072425392
After modification: y = 4.2 id(y) = 2751009746000
In this example, we create an integer variable x and y with a value of 3 and 3.5 and then print its memory location using the id() function. We then modify the value of x to 5 and y to 4.2 and print its memory location again. Notice that the value of x has changed, but its memory location has also changed. This is because integers and floats are immutable in Python, so when we modify the value of x and y, we are actually creating a new integer object as well as a float object in memory with the value of 5 and 4.2 and a different memory location.
3. Strings
# Create a string name = "Alice" # Try to modify the string name[0] = "B" # Raises a TypeError since strings are immutable
Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14404\2554938485.py in
3
4 # Try to modify the string
----> 5 name[0] = "B" # Raises a TypeError since strings are immutable
TypeError: 'str' object does not support item assignment
Mutable v/s Immutable Data Structure
Mutable Data Structures | Immutable Data Structures | |
Definition | Values can be modified | Values cannot be modified |
Example | Lists, sets, dictionaries | Tuples, strings, numbers |
Modification | Elements or values can be added, removed, or modified at any time | Values cannot be modified, instead, new data structure with updated values needs to be created |
Efficiency | More efficient for modifications | Less efficient for modifications |
Security | Less secure as unintended modifications can occur | More secure as values cannot be modified accidentally |
Use Cases | Suitable for situations where data needs to be modified frequently | Suitable for situations where data needs to be protected and not modified |
Library
WEB DEVELOPMENT
FAANG QUESTIONS
On this page
1.
2.
3.
1.
3.
3.