How To Delete Tuple In Python

In this tutorial, you will learn how to delete elements from a tuple in Python. Tuples are immutable and can’t be modified directly, but you can still perform deletions by converting them into a mutable data structure like a list.

We will be looking at how to delete elements from a tuple using different methods, such as removing a single item, deleting multiple elements, and creating a new tuple without the objects you want to remove.

Step 1: Create a Tuple

First, we need to create a tuple with some sample elements. A tuple is a sequence of immutable data types in Python. It is created using parentheses, with elements separated by commas:

Step 2: Deleting a Single Item

Since tuples are immutable, you cannot use the del statement to remove an element directly. However, you can achieve this by converting the tuple into a list, removing the desired element from the list, and then converting it back to a tuple.

Now, new_tuple_single_removed is a new tuple without the element ‘apple’:

(1, 2, 3, 'banana', 'cat')

Step 3: Deleting Multiple Items

To delete multiple items from a tuple, you can use a similar approach. First, convert the tuple into a list, and then use a for loop to remove the unwanted elements. Finally, convert the list back into a tuple:

Now, new_tuple_multiple_removed is a new tuple without the elements 1 and ‘banana’:

(2, 3, 'apple', 'cat')

Step 4: Using List Comprehension

You can also delete elements from a tuple by using list comprehension. In this method, you iterate through the tuple and keep only the elements that you want in the new tuple:

The resulting new_tuple_list_comprehension is:

(2, 3, 'apple', 'cat')

Full Code

Conclusion

In this tutorial, you learned how to delete elements from a tuple in Python. Although tuples are immutable, we can still perform deletions by converting them into mutable data structures, such as lists. Remember to always create a new tuple with the desired elements, as it is not possible to modify the original tuple directly.