Change Values of Python Tuple Items
If you have gone through the tutorial – Python Tuples, you would understand that Python Tuples are immutable. Therefore, you cannot change values of Tuple items. But, there is a workaround.
In this tutorial, we will learn how to update or change tuple values with the help of lists.
The basic difference between a list and tuple in Python is that, list is mutable while tuple is immutable.
So, to change or update Tuple values, we shall convert our tuple to a list, update the required item and then change back the list to a tuple.
Example 1: Change Tuple Values
In this example, we have a Tuple. Following is the step by step process of what we shall do to the Tuple.
- We shall convert the tuple to a list.
- Update the required item of the list.
- Convert the list back to tuple and assign it to the original tuple.
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) #change tuple to list list1 = list(tuple1) #update list list1 = 63 #change back list to tuple tuple1 = tuple(list1) print(tuple1)
(5, 3, 63, 8, 4, 4, 6, 2)
Example 2: Remove item from the Tuple
In this example, we shall remove an item from the tuple, again using List.
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) #change tuple to list list1 = list(tuple1) #remove an item from list list1.remove(2) #change back list to tuple tuple1 = tuple(list1) print(tuple1)
(5, 3, 8, 4, 4, 6, 2)
In this tutorial of Python Examples, we learned how to work around to change the values of items in Python Tuple.