del is a keyword in Python which is used to delete an object. Object can be a list, variable, string, tuple etc. It is differ from the pop() method which returns a value. Here, we are creating various examples to understand its use.
a = "python keyword" print(a) # deleting variable del a print(a)
In the above example, we created a variable a which contains a string value. we first prints a then delete it using Python del keyword. After deleting variable, we print it again and this time, it reports an error. See the below output.
Python del statement can also be used to remove an item from a list, slices from a list or delete entire list object. See the below example.
list1 = [2,4,6,8,10] print(list1) # deleting an item del list1 print(list1) # deleting slice of a list del list1[1:3] print(list1) # deleting list object del list1 print(list1) # Error: due to deletion of list
tup1 = (2,4,6,8) print(tup1) # deleting tuple del tup1 print(tup1)
In this tutorial, we studied about the Python del keyword with the help of various examples. Furthermore you can try it to apply in your Python application and understand its advantage.