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.
Syntax: del object_name
Below are various examples that showcase various use cases of the del
keyword:
Del Keyword for Deleting Objects
In the program below we will delete Sample_class using del Sample_class
statement.
Python3
class Sample_class:
some_variable = 20
def my_method( self ):
print ( "GeeksForGeeks" )
print (Sample_class)
del Sample_class
print (Sample_class)
|
Output:
class '__main__.Sample_class'
NameError:name 'Sample_class' is not defined
Del Keyword for Deleting Variables
In the program below we will delete a variable using del
keyword.
Python3
my_variable1 = 20
my_variable2 = "GeeksForGeeks"
print (my_variable1)
print (my_variable2)
del my_variable1
del my_variable2
print (my_variable1)
print (my_variable2)
|
Output:
20
GeeksForGeeks
NameError: name 'my_variable1' is not defined
Del Keyword for Deleting List and List Slicing
In the program below we will delete a list and slice another list using del
keyword.
Python3
my_list1 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
my_list2 = [ "Geeks" , "For" , "Geek" ]
print (my_list1)
print (my_list2)
del my_list1[ 1 ]
print (my_list1)
del my_list1[ 3 : 5 ]
print (my_list1)
del my_list2
print (my_list2)
|
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
['Geeks', 'For', 'Geek']
[1, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 7, 8, 9]
NameError: name 'my_list2' is not defined
Del Keyword for Deleting Dictionaries and Removing key-value Pairs
In the program below we will delete a dictionary and remove few key-value pairs using del
keyword.
Python3
my_dict1 = { "small" : "big" , "black" : "white" , "up" : "down" }
my_dict2 = { "dark" : "light" , "fat" : "thin" , "sky" : "land" }
print (my_dict1)
print (my_dict2)
del my_dict1[ "black" ]
print (my_dict1)
del my_dict2
print (my_dict2)
|
Output:
{'small': 'big', 'black': 'white', 'up': 'down'}
{'dark': 'light', 'fat': 'thin', 'sky': 'land'}
{'small': 'big', 'up': 'down'}
NameError: name 'my_dict2' is not defined
Please refer delattr() and del() for more details.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Sep, 2023
Like Article
Save Article