Python del

Python del is used to delete the object in Python. Object could be anything, like number, String, list, tuple, set, class etc.

 

Syntax of del

del object_to_be_deleted

 

Example of del

Here we understand del keyword by taking examples.

 

Delete a variable

#Python del keyword

age=10

print (age)

del age

print(age)

 

Output

 

10

NameError: name 'age' is not defined

 

Explanation

age is variable, when first time we print age value it prints 10.

When we print age value after applying del on age. It throws error that “age” is not defined, because del deleted the age variable.

 

del with String, list and tuple

 

#Python del keyword

name = "Python"
list1=[1,2,3]
tuple1=(10,20,30)

print (name, list1,tuple1)

del name
del list1
del tuple1

print (name)
print(tuple1)
print(list1)

 

Output

Python [1, 2, 3] (10, 20, 30)


NameError: name 'name' is not defined

 

 

Explanation:

In Above example, we have string, list and tuple. When del is applied on these it will delete the String, list and tuple objects respectively.

 

 

del with class

 

#Python del with class

class student :
    rollNo=1
    name="Rocky"
    std="5th"
    
 
print(student.name)

del student

print(student.name)

 

Output

 

Rocky


NameError: name 'student' is not defined.



Please follow and like us:
READ  Python Continue