Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

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 −

tup1 = ("a", "b", "c", "d") tup1[2] = 'Z' print ("tup1: ", tup1)

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.

 
tup1 = ("a", "b", "c", "d") print ("Tuple before update", tup1, "id(): ", id(tup1)) list1 = list(tup1) list1[2]='F' list1.append('Z') list1.sort() print ("updated list", list1) tup1 = tuple(list1) print ("Tuple after update", tup1, "id(): ", id(tup1))

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.

Esta resposta foi útil? 1 Utilizadores acharam útil (1 Votos)