Skip to content

del keyword in Python | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading