The del
keyword in Python is primarily used to delete objects in Python. Since everything in Python represents an object in one way or another, The del
keyword can also be used to delete a list, slice a list, delete dictionaries, remove key-value pairs from a dictionary, delete variables, etc. It helps free up memory by removing references to the objects.
Syntax: del object_name
Below are various examples that showcase various use cases of the del
keyword:
Del Keyword for Deleting Objects
Below example will delete Gfg_class using del
statement.
Python
class Gfg_class:
a = 20
# creating instance of class
obj = Gfg_class()
# delete object using del
del obj
# we can also delete class using del keyword
del Gfg_class
Deleting Variables
del keyword can be used to delete variables.
Python
a = 20
b = "GeeksForGeeks"
# you can print and check if a and b exists
# by commenting del statemetns
# delete both the variables
del a, b
# check if a and b exists
print(a)
print(b)
Output:
NameError: name ‘a’ is not defined
Deleting List and Slice
In the program below we will delete a list and slice another list using del
keyword.
Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
# 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, 2, 3, 4, 5, 6, 7, 8, 9]
[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 delete a dictionary and remove few key-value pairs using del
keyword.
Python
d1 = {"small": "big", "black": "white", "up": "down"}
d2 = {"a": 1, "b": 2, "c": 3}
# delete key-value pair with key "black" from my_dict1
del d1["black"]
# check if the key-value pair with key "black" from d1 is deleted
print(d1) # output: {'small': 'big', 'up': 'down'}
# delete d2
del d2
# check if d2 exists
print(d2)
Output:
NameError: name ‘d2’ is not defined
Please refer delattr() and del() for more details.