How to use the del operator on Python tuples

How to Use the Del Operator on Tuples in Python?

A tuple is an immutable, comma-separated collection of Python objects. Similar to lists, tuples are sequences. Tuples differ from lists in that they cannot be modified, whereas lists can, and they use parentheses instead of square brackets.

tup=('Tutorial Point', 'point', 2022, True)
print(tup)

If the above code snippet is executed, the following output will be produced −

('Tutorial Point', 'point', 2022, True)

In this article, we will discuss the use of the del operator on tuples.

del Operator

The del keyword is mostly used in Python to delete objects. Because everything in Python is an object, the del keyword can be used to delete tuples, slice tuples, delete dictionaries, remove key-value pairs from dictionaries, delete variables, and more.

Syntax

del object_name

The del operator on a tuple deletes the entire tuple. Since tuples are immutable, you cannot delete specific elements within a tuple.

Example 1

In the following example, we use the del operator to explicitly delete an entire tuple.

tup=('Tutorial point', 'point', 2022, True)
print(tup)
del(tup)
print("After deleting the tuple: " )
print(tup)

Output

In the following output, you can observe that the del operator has deleted the entire tuple, and when we want to print the tuple after deleting the entire tuple, an error pops up.

('Tutorial point', 'point', 2022, True)
After deleting the tuple:
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(tup)
NameError: name 'tup' is not defined

In a list, we use the del operator to delete a part of the list. Since tuples are immutable, a slice of a tuple cannot be deleted.

Example 2

tup = ("Tutorial Point", "is", "the", "best", "platform", "to", "learn", "new", "skills")
print("Tuple to be deleted">)
print(tup[:5])
del tup[2:5]
print("After deletion: " )
print(tup)

Output

The output of the above code is as follows;

Tuple to be deleted
('the', 'best', 'platform')
Traceback (most recent call last):
File "main.py", line 4, in
del tup[2:5]
TypeError: 'tuple' object does not support item deletion

For more Python-related articles, please read: Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *