MWZ

MINDWAREZONE

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:

  1. Convert the tuple into a list.
  2. Update the required item in the list.
  3. 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

  • list(country) converts the tuple into a list.
  • temp[1] = "Canada" updates the second item.
  • tuple(temp) converts the list back into a tuple.
  • The updated tuple is assigned back to the country variable.

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.