Python Casting a Mutable To Immutable

In Python, mutable objects are those that can be changed after they are created, such as lists or dictionaries. Immutable objects are those that cannot be changed after they are created, such as strings or tuples.

To cast a mutable object to an immutable one, you can use built-in functions that return a new immutable object with the same content as the original mutable object. For example, you can use tuple() to cast a list to a tuple:


my_list = [1, 2, 3] # mutable
my_tuple = tuple(my_list) # immutable
print(my_tuple) # (1, 2, 3)

# Mutable List
lst = [1,2,3,4,5]
lst[0] = 6
print(lst)

# output [6,2,3,4,5]

# Converting It to Immutable

lst = [1,2,3,4,5]
lst2 = tuple(lst)
lst[0] = 6

# output TypeError: 'tuple' object does not support item assignment

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions