Course
Update Tuples
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Update Tuples
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(): 2295023084192updated 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.Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.