In Python, tuple is an immutable data type. An immutable object cannot be modified once it is created in the memory.
Example 1
If we try to assign a new value to a tuple item with slice operator, Python raises TypeError. See the following example −
It will produce the following output −
Traceback (most recent call last): File "C:\Users\mlath\examples\main.py", line 2, in <module> tup1[2] = 'Z' ~~~~^^^ TypeError: 'tuple' object does not support item assignment
Hence, it is not possible to update a tuple. Therefore, the tuple class doesn't provide methods for adding, inserting, deleting, sorting items from a tuple object, as the list class.
How to Update a Python Tuple?
You can use a work-around to update a tuple. Using the list() function, convert the tuple to a list, perform the desired append/insert/remove operations and then parse the list back to tuple object.
Example 2
Here, we convert the tuple to a list, update an existing item, append a new item and sort the list. The list is converted back to tuple.
It will produce the following output −
Tuple before update ('a', 'b', 'c', 'd') id(): 2295023084192
updated list ['F', 'Z', 'a', 'b', 'd']
Tuple after update ('F', 'Z', 'a', 'b', 'd') id(): 2295021518128
However, note that the id() of tup1 before update and after update are different. It means that a new tuple object is created and the original tuple object is not modified in-place.
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.