Mutable vs. Immutable in Python:
Mutable:
Mutable objects are those whose values or content can be changed after creation.
Changes to mutable objects are reflected directly in the memory location where they are stored.
Immutable:
Immutable objects, on the other hand, cannot be changed once they are created.
Any operation that appears to modify an immutable object actually creates a new object with the updated value.
Lists of Mutable and Immutable Data Types:
| Mutable Data Types | Immutable Data Types |
|----------------------|----------------------|
| Lists | Integers |
| Dictionaries | Floats |
| Sets | Strings |
| | Tuples |
Now, let's take an example using a string, which is an immutable data type:
Example with String (Immutable):
# Creating a string
username = "hruthik"
# Displaying the initial value
print(username) # Output: 'hruthik'
# Attempting to change the value of the string
username = "hruthik ks"
# Displaying the updated value
print(username) # Output: 'hruthik ks'
Explanation:
When you create a variable
username
with the value "hruthik" Python allocates a specific memory space for this string.Accessing the content of
username
refers to the memory space where "hruthik" is stored.Strings are immutable, meaning their values cannot be changed after creation.
Attempting to change the value of
username
to "hruthik ks" results in the allocation of a new memory space for this new string.The variable
username
now references the new memory space containing "hruthik ks" while the old reference to "hruthik" still exists.Python's garbage collector automatically identifies and deletes unreferenced objects, such as the memory space containing the original "hruthik" value.
Example with Integer(Immutable):
x = 10
y = x
print(x) # Output: 10
print(y) # Output: 10
x = 15
print(x) # Output: 15
print(y) # Output: 10
Explanation:
When you create an integer variable
x
with the value 10, Python allocates a specific memory space for this integer.Creating a new variable
y
and assigning it the value ofx
(y = x
) makesy
reference the same memory space asx
, both containing the value 10.Modifying the value of
x
to 15 (x = 15
) results in allocating a new memory space for the updated integer value.The variable
x
now references the new memory space containing 15, whiley
retains its reference to the original memory space with the value 10.The values of
x
andy
are now different, withx
holding 15 andy
holding 10.
Creative Explanation:
In Python, think of mutable objects like editable notebooks – you can directly modify what's written inside. On the other hand, immutable objects are like sealed letters; if you want to change the message, you need to create a new letter. Mutable objects allow direct changes in the same space, while immutable objects create a new space for any modifications. This difference impacts how we handle information and memory in Python programs.