Change Tuple Values
A tuple's values are fixed from the moment it is created. That quality is described as unchangeable, or by the term immutable.
There is a way around it, though: turn the tuple into a list, make your change there, then turn the list into a tuple again.
Example
Go through a list to change one of the values:
Output: complete Python program
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items
Immutability also means tuples come without a built-in append() method. You still have other options for adding items.
1. Convert into a list: The trick for changing a tuple works here too. Turn the tuple into a list, add your item(s), then turn the result into a tuple again.
Example
Go through a list to add "orange" to the tuple:
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Example
2. Add tuple to a tuple. Python lets you combine tuples directly. Put the item(s) you want to add, whether one or many, in a new tuple, then add it to the existing one:
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Remove Items
Since tuples are unchangeable, removing an item directly isn't possible. The list workaround from the previous sections does the job here as well:
Example
Go through a list to remove "apple":
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Example
To get rid of a whole tuple, use the del keyword:
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists