The tuple collection is unchangeable (or immutable).
Once a tuple is created in Python, it cannot be changed, which means you cannot add or remove items, but some hacks enable you to do so.
You can convert a tuple into a list, change list items and then convert the list into a tuple.
colors_tuple = ("Red", "Blue", "Green")
colors_list = list(colors_tuple)
colors_list[2] = "Purple"
colors_tuple = tuple(colors_list)
print(colors_tuple)
('Red', 'Blue', 'Purple')
In the above example, a tuple is converted into a list using the list()
constructor, the second index position item is changed, and the list is converted into a tuple using the tuple()
constructor.
You can convert a tuple into a list, add a new item to the list and then convert the list into a tuple.
colors_tuple = ("Red", "Blue", "Green")
colors_list = list(colors_tuple)
colors_list.append("Purple")
colors_tuple = tuple(colors_list)
print(colors_tuple)
('Red', 'Blue', 'Green', 'Purple')
In the above example, a tuple is converted into a list using the list()
constructor, a new item is added to the list using the append()
function, and finally, the list is converted into a tuple using the tuple()
constructor.
It is possible to add tuples to the tuple.
If you want to add new items to the tuple, create a new items tuple and add it to the existing tuple.
colors_tuple = ("Red", "Blue", "Green")
new_colors_tuple = ("Purple",)
colors_tuple = colors_tuple + new_colors_tuple
print(colors_tuple)
('Red', 'Blue', 'Green', 'Purple')
In the above example, we created a new single-item tuple and added it to the existing tuple using a plus (+
) sign.
You can convert a tuple into a list, remove the item from the list and then convert the list into a tuple.
colors_tuple = ("Red", "Blue", "Green")
colors_list = list(colors_tuple)
colors_list.remove("Green")
colors_tuple = tuple(colors_list)
print(colors_tuple)
('Red', 'Blue')
In the above example, a tuple is converted into a list using the list()
constructor, an item removed from the list using the remove()
function, and finally, the list is converted into a tuple using the tuple()
constructor.
The del
keyword completely deletes a tuple.
colors_tuple = ("Red", "Blue", "Green")
del colors_tuple
print(colors_tuple)
NameError: name 'colors_tuple' is not defined
We removed the tuple with the del
keyword, and when we attempted to run the example, it raised an error (NameError: name 'colors_tuple' is not defined
).