del keyword in Python | Example code

Python del keyword is used to delete objects. It could delete everything from an object like variables, lists, dictionaries, slice a list, etc.

del object_name

Examples del keyword in Python

Simple example code to delete variables, lists, dictionaries, and class objects.

Deleting variables

Delete both the variables

num = 10
s = "Hello"

del num
del s

print(num)
print(s)

Output:

del keyword in Python

Deleting list

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

del list1

print(list1)

Output:

NameError: name ‘list1’ is not defined

Deleting dictionaries

dict1 = {"small": "big", "black": "white", "up": "down"}

del dict1

print(dict1)

Output:

NameError: name ‘dict1’ is not defined

Deleting objects

class MyClass:
    name = "John"


del MyClass

print(MyClass)

Output:

NameError: name ‘MyClass’ is not defined

Do comment if you have any questions or suggestions on this Python del keyword topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.