Python del keyword
The del keyword in Python is used to delete objects like variables, lists, dictionary entries, or slices of a list. Since everything in Python is an object, del helps remove references to these objects and can free up memory
del Keyword removes the reference to an object. If that object has no other references, it gets cleared from memory. Trying to access a deleted variable or object will raise a NameError.
Syntax
del object_name
object_name: name of the object to delete (list, set dictionary, etc).
Del Keyword for Deleting Objects
In the example below, we will delete Gfg_class using
del
statement.
class Gfg_class:
a = 20
# creating instance of class
obj = Gfg_class()
# delete object
del obj
# we can also delete class
del Gfg_class
Deleting Variables
del keyword can be used to delete variables too.
a = 20
b = "GeeksForGeeks"
# delete both the variables
del a, b
# check if a and b exists after deleting
print(a)
print(b)
Output:
NameError: name 'a' is not defined
Explanation: del a, b removes the existence of a and b therefore print() funciton is not able to find them.
List Slicing Using del Keyword
In the program below we will delete some parts of a list (basically slice the list) using del keyword.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# delete second element of 'a'
del a[1]
# check if the second element in 'a' is deleted
print(a)
# slice 'a' from index 3 to 5
del a[3:5]
# check if the elements from index 3 to 5 in 'a' is deleted
print(a)
Output
[1, 3, 4, 5, 6, 7, 8, 9] [1, 3, 4, 7, 8, 9]
Deleting Dictionary and Removing key-value Pairs
In the program below we will remove few key-value pairs from a dictionary using del keyword.
d = {"small": "big", "black": "white", "up": "down"}
# delete key-value pair with key "black" from my_dict1
del d["black"]
# check if the key-value pair with key "black" from d1 is deleted
print(d)
Output
{'small': 'big', 'up': 'down'}