Update Tuples Items
What You'll Learn: In this tutorial, you'll discover how to work around the immutability of tuples in Python. Although tuples are unchangeable, there are tricks to modify, add, or remove items.
Change Tuple Values
Once a tuple is created, its values cannot be changed. Tuples are immutable. However, you can work around this by converting the tuple to a list, changing the list, and converting it back into a tuple.
Example Code:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Output: ('apple', 'kiwi', 'cherry')
Add Items to a Tuple
Since tuples are immutable, they do not have a built-in append() method, but you can still add items by using one of the following methods:
Convert to a List and Back: Convert the tuple to a list, add your items, and convert it back to a tuple.
Example Code:
pythonthistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange") thistuple = tuple(y) print(thistuple)- Output:
('apple', 'banana', 'cherry', 'orange')
- Output:
Add a Tuple to a Tuple: You can add one tuple to another.
Example Code:
pythonthistuple = ("apple", "banana", "cherry") y = ("orange",) thistuple += y print(thistuple)- Output:
('apple', 'banana', 'cherry', 'orange')
Note: When creating a tuple with a single item, always include a comma after the item.
- Output:
Remove Items from a Tuple
Tuples are immutable, so you cannot remove items directly. However, you can convert the tuple to a list, remove the items, and convert it back to a tuple.
Example Code:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)- Output:
('banana', 'cherry')
Deleting a Tuple Completely: You can delete the entire tuple using the del keyword.
Example Code:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) - Output:
This will raise an error because the tuple no longer exists
Try It Yourself: Fun Exercises
- Update Your Favorite Movies:
- Create a tuple of your favorite movies.
- Convert it to a list, change a movie, and convert it back to a tuple.
- Add a New Fruit:
- Write a tuple of fruits.
- Add a new fruit by converting to a list or using the tuple addition method.
Summary:
In this Python tutorial, we learned how to work around the immutability of tuples to change, add, or remove items. These techniques involve converting tuples to lists and back. Keep experimenting and have fun with tuples in Python!