You are reading the article Mutable &Amp; Immutable Objects In Python {Examples} updated in October 2023 on the website Vibergotobrazil.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested November 2023 Mutable &Amp; Immutable Objects In Python {Examples}
What is a Mutable Object?Mutable in Python can be defined as the object that can change or be regarded as something changeable in nature. Mutable means the ability to modify or edit a value.
Mutable objects in Python enable the programmers to have objects that can change their values. They generally are utilized to store a collection of data. It can be regarded as something that has mutated, and the internal state applicable within an object has changed.
What are Immutable objects?These objects become permanent once created and initialized, and they form a critical part of data structures used in Python.
Python is used in numbers, tuples, strings, frozen sets, and user-defined classes with some exceptions. They cannot change, and their values and it remains permanent once they are initialized and hence called immutable.
In Python, everything is an object
In the Python programming language, everything can be regarded as an object comprising lists, integers, and functions. This feature can be compared with other programming languages which support objects.
This feature can be verified using a Python interpreter as shown below: –
Python code:
print("The following instance is an object:",isinstance(3,object)) print("Another instance for object", isinstance(True, object)) def my_func(): return "guru99" print("This is a function example and regarded as an object in Python:", isinstance(my_func, object))Output:
A following instance is an object: True Another instance for object True This is a function example and regarded as an object in Python: TrueFurther, Python provides a built-in function named id that returns the object’s address as present in the memory of the Python programming language.
Python code:
z=200 id(z) print("The id of object is", id(z))Output:
the id of object is 9795360In the above code, the id function having syntax as id(obj) gives the address of obj in Python memory. Here, there is an object named z, and it has an assignment of 200. The object z is then passed into id function as id(z), and the Python delivers the object’s address as 9795360.
Mutable objects in PythonIn a mutable object, the object’s value changes over a period of time.
In this example, we have explained mutable objects in Python, and this utilizes lists as an application of mutable objects as shown below: –
Python Code:
mut_list = [1, 2, 3] print("The list in Python",mut_list) mut_list[0] = 'Gurru99' mut_list print("The list in Python after changing value",mut_list)Output:
The list in Python [1, 2, 3] The list in Python after changing value ['Gurru99', 2, 3]As we can see in the above-given example, the mutable list in Python had values of 1,2,3. The first element of the mutable list is changed from 1 to Guru99, and it does not create a new object when a new value is initialized.
Here we can use the id method to utilize it. Following illustrates the use of the id method for mutable objects as shown below: –
Python Code:
mut_list = [1, 2, 3] print("The list in Python",mut_list) print("the id of the list is ",id(mut_list)) mut_list[0] = 'Gurru99' mut_list print("The mut list in Python after changing value",mut_list) print("the id of the list is post change in value",id(mut_list))Output
The list in Python [1, 2, 3] the id of the list is 139931568729600 The list in Python after changing value ['Gurru99', 2, 3] the id of the list is post change in value 139931568729600The following figure illustrates the mutable object in Python as shown below: –
Immutable objects in PythonImmutable objects in Python are objects wherein the instances do not change over the period. Immutable instances of a specific type, once created, do not change, and this can be verified using the id method of Python.
Let us take an example of integer type objects in Python that illustrates the concept of immutable objects in Python as shown below: –
Python Code:
a=244 print("the number before change is",a) print("the id of number before change is",id(a)) a=344 print("the number after change is",a) print("the id of number after change is",id(a))Output
the number before a change is 244 the id of number before change is 9796768 the number before change is 344 the id of number before change is 140032307887024It could be seen above that there is change in “a.” Let’s study how the mechanism works:
There is no change in the object’s value when the initialization of “a” with 344.
Instead, a new object is created and is bounded with “a.”
The other object assigned as 244 would no longer be accessible.
The above example utilized an integer object.
At a=244, a new object is created and referenced to “a” as shown below: –
Post using a=344, there is a new object referenced with “a”. The following diagram represents the same: –
Therefore, whenever there is the assignment of a new value to the name of int type, there is a change in the binding of the name with another object. The same principle aligns with tuples, strings, float, and Boolean hence termed immutable.
Implications for dictionary keys in PythonDictionaries can be defined as the ordered collections that stores data in the key format and does not allow duplicates. Dictionaries contains one key which have corresponding value pair aligned to it. They are mutable in types, and their content can be changed even after their initialization and creation.
At any moment, the key points to one specific element at a time. The keys of dictionaries are immutable.
Let us take a hypothetical scenario as shown below: –
a = [4, 6] b = [5, 6, 7] my_dict = {a: 'x', b: 'y'} print(my_dict)Output: – The above Python code does not yield any output, and instead, it generates a type error of unhashable type. This is a hypothetical situation and is not used in the Python compiler.
Here, a is defined as [4,6], and in the dictionary, it is defined as x. Here, b is defined as [5,6,7], and in the dictionary, it is defined as y.
The key ‘a’ has the value of [4,6], and it is further initialized to x.
The key ‘b’ has the value of [5,6,7] which is further initialized to ‘y’ in a dictionary.
Now assume that the value of ‘a’ is appended with 5 and 7, which is a key for the dictionary.
Then the dictionary has been mutated, and it would give both ‘x’ and ‘y’ as values for the above dictionary.
Consider the following scenario as illustrated above: –
a = [5, 6,7] b = [5, 6, 7] my_dict = {a: 'x', b: 'y'} print(my_dict)Hence, as a programming language, Python makes keys of the dictionary immutable, and dictionaries are immutable data types.
Exceptions in immutabilityHowever, Python provides exceptions to immutability such exceptions can be observed for the tuple object type. A tuple can be a combination of mutable and immutable object types. Let us take an example to explain the exceptions in immutability as shown below: –
Python Code:
tupexample=([1,1],'guru99') print("the tuple before change",tupexample) print("the id of tuple before change",id(tupexample)) tupexample=([2,2],'guru99') print("the tuple after change",tupexample) print("the id of tuple after change",id(tupexample))Output:
the tuple before change ([1, 1], 'guru99') the id of tuple before change 140649480694656 the tuple after change ([2, 2], 'guru99') the id of tuple after change 140649480694592You can see in the above code, that the first element, which is a list, is mutable, whereas the tuple is immutable. The value of the tuple cannot be changed, but the contents of the list present inside the tuple can change its value.
Therefore, this raises an exception that the immutable objects do not change their value, but the value of constituents changes their value.
Mutable vs. Immutable objectsHere are major differences between Mutable and Immutable Objects:
Mutable object Immutable object
The object state can be changed once created The object state cannot be changed once created
Mutable objects are not regarded as thread-safe in nature. Immutable objects are regarded as thread-safe in nature.
The mutable objects are not made final, and hence the programmer can keep changing mutable objects and use the same objects. It is critical to make classes final when there is the creation of the immutable object
Python Immutable Data TypesClass Explanation Immutable or not
Bool Boolean value Immutable
Int Integer value (magnitude can be arbitrary) Immutable
Float Floating point number Immutable
List Sequence of objects of mutable nature Mutable
Tuple Sequence of objects of immutable nature Immutable
Str Character /string Immutable
Set set of distinct objects that are of Unordered nature Mutable
Frozenset Set class of immutable nature Immutable
Dict Dictionary or associative mapping Mutable
You're reading Mutable &Amp; Immutable Objects In Python {Examples}
Update the detailed information about Mutable &Amp; Immutable Objects In Python {Examples} on the Vibergotobrazil.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!