Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Mutable vs

Uploaded by

pakijabangles786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Mutable vs

Uploaded by

pakijabangles786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Mutable vs.

Immutable
Data Types
Mutable and Immutable Data Types in
Python
Mutable or immutable is the fancy word for
explaining the property of data types of being able
to get updated after being initialized. The basic
explanation is thus: A mutable object is one whose
internal state is changeable. On the contrary, once
an immutable object in Python has been created, we
cannot change it in any way.

What are Mutable Data Types?


Anything is said to be mutable when anything can be
modified or changed. The term "mutable" in Python
refers to an object's capacity to modify its values.
These are frequently the things that hold a data
collection.

What are Immutable Data Types?


Immutable refers to a state in which no change can
occur over time. A Python object is referred to as
immutable if we cannot change its value over time.
The value of these Python objects is fixed once they
are made.
List of Mutable and Immutable objects
Python mutable data types:
Advertisement

o Lists
o Dictionaries
o Sets
o User-Defined Classes (It depends on the user to
define the characteristics of the classes)
Python immutable data types:

o Numbers (Integer, Float, Complex, Decimal,


Rational & Booleans)
o Tuples
o Strings
o Frozen Sets

The Python id() Function


When you define a Python object, the program sets
a memory section aside. Every Python object has a
distinct address that informs the application where
the item is located in memory.
Every object in Python has a distinct ID connected to
the object's memory address. Use the built-in Python
id() function to read the special ID.
Let's read the position of a sample string object in
memory, for instance:
Code

1.# Python program to show how to use the id functio


n
2.
3.# Initializing a string object
4.string = "string"
5.
6.# Printing the id of the string object
7.print(id(string))
Output:
140452604995952

Mutability in Python
As we have already told, an immutable Python
object cannot be altered.
In Python, the integer data type is a prime case of
an immutable object or data type. Let's conduct an
easy experiment to understand this.
Let's first make two integer variables, x and y. The
variable y is a reference to the variable x:
Now, x and y both point towards the same location
in memory. In other words, both integer variables
should have the same ID returned by the id()
function. Let's confirm that this is true:
Code

1.# Python program to create two variables having the


same memory reference
2.
3.# Initializing a variable
4.x = 3
5.
6.# Storing it in another variable
7.y = x
8.
9.# Checking if two have the same id reference
10. print("x and y have same id: ", id(x) == id(y))
Output:
x and y have same id: True

As a result, the variables x and y points to a single


integer object. In other words, even though there is
just one integer variable, two variables refer to it.
Let us change x's value now. Next, let's compare the
reference ids of x and y once more:
Code

1.# Python program to check if x and y have the same


ids after changing the value
2.
3.x = 3
4.y = x
5.
6.# Changing the value of x
7.x = 13
8.
9.# Checking if x and y still point to the same memory
location
10. print("x and y have the same ids: ", id(x) == id(
y))
Output:
x and y have the same ids: False

This is because x now points to a distinct integer


object. Therefore, the integer variable 3 itself
remained constant. However, the variable x that
previously referred to it now directs users to the new
integer entity 13.
Therefore, even though it appears like we modified
the original integer variable, we didn't. In Python,
the integer object is an immutable data type,
meaning that an integer object cannot be changed
once created.
Let's conduct a similar test once more using a
mutable object.
Create a list, for instance, and put it in a second
variable. Then, compare the reference IDs of the two
lists. Let's then make some changes to the list we
created. Then, let's see if the reference IDs of both
lists still coincide:
Code

1.# Python program to check if the lists pointing to the


same memory location will have the same reference
ids after modifying one of the lists
2.
3.# Creating a Python list object
4.num = [2, 4, 6, 8]
5.
6.# Storing the list in another variable
7.l = num
8.
9.# Checking if the two variables point to the same m
emory location
10. print("Both list variables have the same ids: ", i
d(num) == id(l))
11.
12. # Modifying the num list
13. num.append(10)
14.
15. # Checking if, after modifying num, both the list
s point to the same memory location
16. print("Both list variables have the same ids: ", i
d(num) == id(l))
Output:
Both list variables have the same ids: True
Both list variables have the same ids: True

Furthermore, their reference IDs match. As a result,


the list objects num and l point to the memory
location. This demonstrates that we could explicitly
change the list object by adding one more element.
The list data structures must therefore be mutable.
And Python lists operate in this way.

Example of Mutable Objects in Python


List
As a result of their mutable nature, lists can change
their contents by incorporating the assignment
operators or the indexing operators.
Let's look at an example of that.
Code

1.# Python program to show that a list is a mutable da


ta type
2.
3.# Creating a list
4.list1 = ['Python', 'Java', 23, False, 5.3]
5.print("The original list: ", list1)
6.
7.# Changing the value at index 2 of the list
8.list1[2]='changed'
9.print("The modified list: ", list1)
Output:
The original list: ['Python', 'Java', 23, False, 5.3]
The modified list: ['Python', 'Java', 'changed', False, 5.3]

Dictionary
Due to the mutability of dictionaries, we can modify
them by implementing a built-in function update or
using keys as an index.
Let's look at an illustration of that.
Code

1.# Python program to show that a dictionary is a mut


able data type
2.
3.# Creating a dictionary
4.dict_ = {1: "a", 2: "b", 3: "c"}
5.print("The original dictionary: ", dict_)
6.
7.# Changing the value of one of the keys of the dictio
nary
8.dict_[2]= 'changed'
9.print("The modified dictionary: ", dict_)
Output:
The original dictionary: {1: 'a', 2: 'b', 3: 'c'}
The modified dictionary: {1: 'a', 2: 'changed', 3: 'c'}

Set
Due to the mutability of sets, we can modify them
using a built-in function (update).
See an illustration of that:
Code

1.# Python program to show that a set is a mutable da


ta type
2.
3.# Creating a set
4.set_ = {1, 2, 3, 4}
5.print("The original set: ", set_)
6.
7.# Updating the set using the update function
8.update_set = {'a', 'b', 'c'}
9.set_.update(update_set)
10. print("The modified set: ", set_)
Output:
The original set: {1, 2, 3, 4}
The modified set: {1, 2, 3, 4, 'b', 'a', 'c'}

Example of Immutable Python Objects


int
Since int in Python is an immutable data type, we
cannot change or update it.
As we previously learned, immutable objects shift
their memory address whenever they are updated.
Here is an illustration of that:
Code
1.# Python program to show that int is an immutable
data type
2.
3.int_ = 25
4.print('The memory address of int before updating: ',
id(int_))
5.
6.# Modifying an int object by giving a new value to it
7.int_ = 35
8.print('The memory address of int after updating: ', i
d(int_))
Output:
The memory address of int before updating: 11531680
The memory address of int after updating: 11532000

float
Since the float object in Python is an immutable data
type, we cannot alter or update it. As we previously
learned, immutable objects shift their memory
address whenever they are updated.
Here is an illustration of that:
Code
1.# Python program to show that float is an immutabl
e data type
2.
3.float_ = float(34.5)
4.print('The memory address of float before updating:
', id(float_))
5.
6.# Modifying the float object by giving a new value to
it
7.float_ = float(32.5)
8.print('The memory address of float after updating: ',
id(float_))
Output:
The memory address of float before updating: 139992739659504
The memory address of float after updating: 139992740128048

String
Since strings in Python are immutable data
structures, we cannot add or edit any data. We
encountered warnings stating that strings are not
changeable when modifying any section of the
string.
Here is an illustration of that:
Code
1.# Python program to show that a string is an immut
able data type
2.
3.# Creating a string object
4.string = 'hello peeps'
5.
6.# Trying to modify the string object
7.string[0] = 'X'
8.print(string)
Output:
TypeError Traceback (most recent call last)
<ipython-input-3-4e0fff91061f> in <module>
3 string = 'hello peeps'
4
----> 5 string[0] = 'X'
6
7 print(string)

TypeError: 'str' object does not support item assignment

Tuple
Because tuples in Python are immutable by nature,
we are unable to add or modify any of their
contents. Here is an illustration of that:
Code

1.# Python program to show that a tuple is an immuta


ble data type
2.
3.# Creating a tuple object
4.tuple_ = (2, 3, 4, 5)
5.
6.# Trying to modify the tuple object
7.tuple_[0] = 'X'
8.print(tulple_)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-e011ebc4971e> in <module>
5
6 # Trying to modify the tuple object
----> 7 tuple_[0] = 'X'
8 print(tulple_)
9

TypeError: 'tuple' object does not support item assignment

FrozenSet
Like sets, frozensets are immutable data structures.
While the set's components can always be changed,
this cannot be done with a frozenset. Therefore,
nothing can be added to or updated in the frozenSet.
Here is an illustration of that:
Code

1.# Python program to show that a frozenset is an im


mutable data type
2.
3.# Creating a frozenset object
4.t = (2, 4, 5, 7, 8, 9, 5, 9, 6, 11, 12)
5.fset = frozenset(t)
6.
7.# Updating the value of the frozenset
8.fset[1] = 76
9.print(fset)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-2cafcda94faf> in <module>
6
7 # Updating the value of the frozenset
----> 8 fset[1] = 76
9 print(fset)
10

TypeError: 'frozenset' object does not support item assignment

You might also like