Python Tutorial Python Advanced Python References Python Libraries

Python del Keyword



The Python del keyword is used to delete objects. As everything in Python is an object, hence, del keyword can also be used to delete variables, sequence, iterable and it's elements.

Syntax

del object

Example: delete an object

In the example below, del keyword is used to delete a given dictionary object.

Info = {
  "name": "John",
  "age": 25,
  "city": "London"
}

del Info
print(Info)

The output of the above code will be:

Traceback (most recent call last):
  File "Main.py", line 8, in <module>
    print(Info)
NameError: name 'Info' is not defined

Example: delete part of sequence and variables

In the example below, del keyword is used to delete a part of a given list object. The del keyword can also be used to delete a variable.

MyList = [1, 2, 3, 4, 5, 6]
del MyList[1:4]
print(MyList)

MyString = 'John'
del MyString
print(MyString)

The output of the above code will be:

[1, 5, 6]

Traceback (most recent call last):
  File "Main.py", line 7, in <module>
    print(MyString)
NameError: name 'MyString' is not defined

❮ Python Keywords