How does the del operator work on a tuple in Python?


A tuple is an ordered and immutable collection of Python objects separated by commas. Like lists, tuples are sequences. Tuples differ from lists in that they can't be modified, whereas lists can, and they use parentheses instead of square brackets.

tup=('tutorials', 'point', 2022,True) print(tup)

If you execute the above snippet, produces the following output −

('tutorials', 'point', 2022, True)

In this article, we discuss about the use of the del operator on a tuple.

The 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 a tuple, slice a tuple, delete dictionaries, remove key-value pairs from a dictionary, delete variables, and so on.

Syntax

del object_name

The del operator in the tuple is used to delete the entire tuple. As tuples are immutable they cannot delete a particular element in a tuple.

Example 1

In the following example, we explicitly remove an entire tuple using the del operator.

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

Output

In the below 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 is popped up.

('tutorials', '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 lists, we use the del operator to delete a part of the list. As tuples are immutable, we cannot delete a slice of a tuple

Example 2

tup = ("Tutorialspoint", "is", "the", "best", "platform", "to", "learn", "new", "skills") print("The below part of the tuple needs to be deleted") print(tup[2:5]) del tup[2:5] print("After deleting:") print(tup)

Output

The output of the above code is as follows;

The below part of the tuple needs 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

Updated on: 02-Nov-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements