The Python del keyword is used to delete objects. Its syntax is:
# delete obj_name
del obj_name
Here, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc.
Example 1: Delete an user-defined object
In the program, we have deleted MyClass using del MyClass statement.
Example 2: Delete variable, list, and dictionary
Example 3: Remove items, slices from a list
The del statement can be used to delete an item at a given index. It can also be used to remove slices from a list.
Example 4: Remove a key:value pair from a dictionary
del With Tuples and Strings
Note: You can't delete items of tuples and strings in Python. It's because tuples and strings are immutables; objects that can't be changed after their creation.
my_tuple = (1, 2, 3)
# Error: 'tuple' object doesn't support item deletion
del my_tuple[1]
However, you can delete an entire tuple or string.
my_tuple = (1, 2, 3)
# deleting tuple
del my_tuple