Python del Statement

Introduction

In Python, the del keyword is generally used to delete an object. Since everything in Python represents some kind of object, the del keyword can also be used to delete lists, variables, parts of a list, etc. The del statement does not return any type of value.

Syntax of del statement

Note: del is a keyword, and obj_name can be lists, dictionaries, user-defined objects, variables, etc.

Examples of del Statement

Let's look at some examples of del statements and try to delete some items.

Example 1: In this program we will delete a variable using del statement

Output:

35

Traceback (most recent call last):
  File "", line 10, in 
NameError: name 'c' is not defined
>

Python del Statement

Example 2: In this program we will delete a list and slice list using del keyword

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
['a', 'b', 'c', 'd', 'e', 'f']
[0, 1, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 3, 4]
['a', 'c', 'd', 'e', 'f']

Traceback (most recent call last):
  File "", line 30, in 
NameError: name 'items_2' is not defined
>

Python del Statement

Example 3: In this program, we will use the del statement to delete dictionaries and key-value pairs

Output:

{'up': 'down', 'forward': 'backward', 'small': 'down'}
{'short': 'long', 'you': 'me', 'Jack': 'John'}
{'forward': 'backward', 'small': 'down'}

Traceback (most recent call last):
   File "", line 18, in 
NameError: name 'dictionary_2' is not defined
>

Python del Statement

Example 4: Delete a User-Defined Object

Output:

Name:  John wik
Age:  26
Address:  C-26, London
Phone No:  61562347
Traceback (most recent call last):
   File "", line 21, in 
NameError: name 'emp' is not defined
>

Python del Statement




Latest Courses