Python - Update Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
For example, the following code will produce an error:
country = ("Spain", "India", "US", "Germany")
country[1] = "Canada"
Output:
TypeError: 'tuple' object does not support item assignment
How to Update a Tuple
Although you cannot update a tuple directly, you can achieve the same result by following these steps:
- Convert the tuple into a list.
- Update the required item in the list.
- Convert the list back into a tuple.
Example: Update a Tuple Item
country = ("Spain", "India", "US", "Germany")
# Convert tuple to list
temp = list(country)
# Update an item
temp[1] = "Canada"
# Convert list back to tuple
country = tuple(temp)
print(country)
Output:
('Spain', 'Canada', 'US', 'Germany')
Explanation
-
converts the tuple into a list.list(country) -
updates the second item.temp[1] = "Canada" -
converts the list back into a tuple.tuple(temp) -
The updated tuple is assigned back to the
countryvariable.
Updating Multiple Items
You can also update more than one item before converting the list back into a tuple.
temp = list(country)
temp[0] = "France"
temp[2] = "Japan"
country = tuple(temp)
print(country)
Output:
('France', 'India', 'Japan', 'Germany')
Note: Every time you update a tuple, Python actually creates a new tuple. The original tuple remains unchanged.