In this section, we will learn what the del operator is and how to use it in Python.
del Operator in Python
The `del` operator is used to delete objects in Python.
We know that in Python everything is an object! So that means we can use this operator to delete any type of object. For example, a variable that is pointing to a value, a List, an element of a List, a Dictionary, a key of a dictionary, a Tuple, etc.
Note: Although we can remove a tuple object using the del operator, we can’t use this operator to remove an element of tuple object!
del Operator in Python Syntax:
del object_name
On the right side of this operator, we put the object we want to remove from our program.
Example: deleting a variable in python with del operator
var1 = 10 var2 = "String" var3 = True del var1 del var2 del var3
Example: deleting a list in python with del operator
list1 = [1,2,3,4,5,6,7,8] del list1[0] del list1[1] del list1[2] print(list1) del list1
Output:
[2, 4, 6, 7, 8]
Example: removing items and slices from a list in python with del operator
list1 = [1,2,3,4,5,6,7,8] del list1[1] del list1[0:4] print(list1) del list1
Output:
[6, 7, 8]
Example: removing keys from a dictionary in python with del operator
employee = { "name":"John", "lastName":"Doe", "age":20, "email":"[email protected]" } del employee["name"] del employee["lastName"] print(employee)
Output:
{'age': 20, 'email': '[email protected]'}