Python del Statement - How to delete a variable or an object in Python?

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.

Python del Example: deleting a variable

a = "python keyword"


# deleting variable
del 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 keyword
NameError: name 'a' is not defined

Python del Example: deleting a list

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]

# deleting an item
del list1[0]

# deleting slice of a list
del list1[1:3]

# deleting list object
del list1
print(list1) # Error: due to deletion of list


[2, 4, 6, 8, 10]
[4, 6, 8, 10]
[4, 10]
NameError: name 'list1' is not defined

Python del Example: deleting tuple in python

tup1 = (2,4,6,8)

# deleting tuple
del tup1


(2, 4, 6, 8)
NameError: name 'tup1' is not defined


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.

Useful Resources: