Update Tuple


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.

Examples

1. Update a Tuple item using a list

In this example, we have a Tuple. Following is the step by step process of what we shall do to the Tuple.

  1. We shall convert the tuple to a list.
  2. Update the required item of the list.
  3. Convert the list back to tuple and assign it to the original tuple.

Python Program

tuple1 = (5, 3, 2, 8, 4, 4, 6, 2)

#change tuple to list
list1 = list(tuple1)

#update list
list1[2] = 63

#change back list to tuple
tuple1 = tuple(list1)

print(tuple1)

Output

(5, 3, 63, 8, 4, 4, 6, 2)

2. Remove item from a given Tuple

In this example, we shall remove an item from the tuple, again using List.

Python Program

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)

Output

(5, 3, 8, 4, 4, 6, 2)

Summary

In this tutorial of Python Examples, we learned how to work around to change the values of items in Python Tuple.