Join our newsletter for the latest updates.

Python del Statement

In this tutorial, you will learn to use the del keyword with the help of examples.

The syntax of the del statement is:

del obj_name

Here, del is a Python keyword. And, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc.

Example 1: Delete an user-defined object

class MyClass:
    a = 10
    def func(self):

# Output: 

# deleting MyClass
del MyClass

# Error: MyClass is not defined

In the program, we have deleted MyClass using del MyClass statement.

Example 2: Delete variable, list, and dictionary

my_var = 5
my_tuple = ('Sam', 25)
my_dict = {'name': 'Sam', 'age': 25}

del my_var
del my_tuple
del my_dict

# Error: my_var is not defined

# Error: my_tuple is not defined

# Error: my_dict is not defined

Example 3: Remove items, slices from a list

The del statement can be used to delete an item at a given index. Also, it can be used to remove slices from a list.

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

# deleting the third item
del my_list[2]

# Output: [1, 2, 4, 5, 6, 7, 8, 9]

# deleting items from 2nd to 4th
del my_list[1:4]

# Output: [1, 6, 7, 8, 9]

# deleting all elements
del my_list[:]

# Output: []

Example 4: Remove a key:value pair from a dictionary

person = { 'name': 'Sam',
  'age': 25,
  'profession': 'Programmer'

del person['profession']

# Output: {'name': 'Sam', 'age': 25}

You can't delete items of tuples and strings. It's because tuples and strings are immutables; objects that can't be changed after its creation.

my_tuple = (1, 2, 3)

# Error: 'tuple' object doesn't support item deletion
del my_tuple[1]

However, you can delete an entire tuple or string.

my_tuple = (1, 2, 3)

# deleting tuple
del my_tuple
Did you find this article helpful?