Differentiate between mutable and immutable data types in Python
Mutable and immutable data types
In Python, data types can be categorized as mutable or immutable based on their behavior when values are modified. The distinction between mutable and immutable data types affects how variables are modified and memory is managed.
Mutable Data Types:
Mutable data types are those whose values can be changed after creation. The memory location of a mutable object remains unchanged when it is modified in-place. As a result, all references to that object will change.
Examples of mutable data types in Python include:
- list: Lists are ordered collections that can be modified by adding, removing, or changing elements.
- dict: Dictionaries are collections of key-value pairs, and we can add, remove, or modify items using their keys.
- set: Sets are unordered collections of unique elements, and we can add or remove elements from them.
Example of a mutable data type (list):
Code:
list_nums = [10, 20, 30, 40]
list_nums.append(40) # Modifying the list by adding an element
print(list_nums) # Output: [10, 20, 30, 40]
Output:
[10, 20, 30, 40, 40]
Immutable Data Types:
Immutable data types are those whose values cannot be changed after creation. When you modify an immutable object, you create a new object with the modified value, and the original object remains unchanged. As a result, any variables referencing the original object won't be updated.
Examples of immutable data types in Python include:
- int: Integer data type represents whole numbers, and once created, their value cannot be changed.
- float: Floating-point data type represents real numbers and is immutable.
- str: String data type represents a sequence of characters, and you cannot change its individual characters.
- tuple: A tuple is an ordered collection, similar to a list, but their elements cannot be modified once they have been created.
Example of an immutable data type (string):
Code:
str1 = "Python"
new_str1 = str1.lower() # Creating a new string with all lowercase characters
print(str1) # Output: "Python" (Original string remains unchanged)
print(new_str1) # Output: "python" (New string with modifications)
Output:
Python Python
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/differentiate-between-mutable-and-immutable-data-types-in-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics