Javaexercise.com

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"

print(a)

# deleting variable
del a

print(a)

In the above example, we created a variable 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.

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]
print(list1)

# deleting an item
del list1[0]
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

Output:

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

 

Python del Example: deleting tuple

tup1 = (2,4,6,8)
print(tup1)

# deleting tuple
del tup1
print(tup1)

Output:

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

 

Conclusion

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.