Home »
Python
del keyword with example in Python
Python del keyword: Here, we are going to learn about the del keyword with example.
Submitted by IncludeHelp, on April 14, 2019
Python del keyword
del is a keyword (case-sensitive) in python, it is used to delete an object (like class's object, variable, list, part of the list, etc).
Note: After deleting an object – if you try to use it, a "NameError" occurs.
Syntax of del keyword
del object_name
Example:
Input:
num = -21
# deleting
del a
# trying to print - an error will occur
print(num)
Output:
NameError: name 'num' is not defined
Python examples of del keyword
Example 1: Delete a variable.
# python code to demonstrate example of
# del keyword
# Delete a variable
# declare a variable & assign a value
a = 100
# printing the value
print("a = ", a)
# deleting the variable
del a
# Printing the value - NameError will be generated
print("a = ", a)
Output
a = 100
Traceback (most recent call last):
File "/home/main.py", line 17, in <module>
print("a = ", a)
NameError: name 'a' is not defined
Example 2: Delete a class's object.
# python code to demonstrate example of
# del keyword
# Delete a class's object
# defining a class
class student:
name = "Aman"
age = 21
# main code
# declaring object to the student class
std = student()
# printing values
print("Name: ", std.name)
print("Age: ", std.age)
# deleting the object
del std
# printing values - will generate NameError
print("Name: ", std.name)
print("Age: ", std.age)
Output
Name: Aman
Age: 21
Traceback (most recent call last):
File "/home/main.py", line 23, in <module>
print("Name: ", std.name)
NameError: name 'std' is not defined