0% found this document useful (0 votes)
17 views

Mutable and Imutable Data Types

The document discusses mutable and immutable objects in Python. Immutable objects like integers, floats, strings and tuples cannot be changed once created, while mutable objects like lists and dictionaries can be modified. Code examples are provided to test immutability of tuples and strings as well as mutability of lists.

Uploaded by

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

Mutable and Imutable Data Types

The document discusses mutable and immutable objects in Python. Immutable objects like integers, floats, strings and tuples cannot be changed once created, while mutable objects like lists and dictionaries can be modified. Code examples are provided to test immutability of tuples and strings as well as mutability of lists.

Uploaded by

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

Mutable vs Immutable data types

Mutable vs Immutable Objects in Python

Every variable in python holds an instance of an object.


There are two types of objects in python
i.e. Mutable and Immutable objects.

Immutable Objects :
An immutable object can’t be changed after it is created.
These are of in-built types like int, float, bool, string, tuple.

Mutable Objects :
A mutable object can be changed after it is created.
These are of type List, dictionary, Set .
# Python code to test that tuples are immutable

tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Output:

Error:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
# Python code to test that strings are immutable

message = "Welcome to python classes"


message[0] = 'p'
print(message)

Output:
Error :
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
# Python code to test that Lists are mutable

color = ["red", "blue", "green"]


print(“List before updating :” , color)

color[0] = "pink"
color[-1] = "orange"
print(“List after updating:” , color)

Output:
List before updating : ["red", "blue", "green"]
List after updating : [“pink", “blue", “orange"]

You might also like