Methods and Functions

Python del Statement (with Examples)

Every variable, function, data structure, a user-defined object created by the programmer in Python can be deleted. After a programmer has defined these iterable objects, their existence can be removed from the program. The reasons for doing this can be many – to save memory space, to increase compilation time, to increase coding efficiency, to reuse the object names with a fresh set of data values, etc. Python provides the user with a keyword to perform such functionalities. Python del keyword is used to delete objects in the program.

Definition

  • Python del is a keyword used to delete any element, objects in a Python program.
  • The Python del statement is used to delete a variable from the local or global namespace from the program.

Python del Statement

In Python, everything is an object, with attributes and functions in practically everything. Python del’s primary goal is to destroy objects in the Python programming language. The del statement is used to delete a name from the scope of the program. When the del statement is used on a name, that name’s identity is gone. Any subsequent references to it will throw a NameError exception.

Syntax

where,

del = Python keyword for deleting an object.

obj_name = name of the iterable objects that can be lists, tuples, dict, variables, user-defined objects, etc.

Note By referring to an item’s index rather than its value, the del statement can be used to delete it from a list.

The Python del statement can be used in several different contexts, for example –

  • To delete a variable name from the local scope and the global scope
  • To delete an item or a data value from the list, set, dictionary, or any other mutable iterables in Python.
  • Attributes of the class instances can be deleted.
  • To remove a slicing from a list of iterables.

Delete a User-Defined Object

In the below program, we have created a class that prints the value of a variable. The first print statement displays all the values of the class variables. In order to delete the existence of this class, we use the del statement. And then again when we use the print statement using the same class name, the Python compiler will show an error. Look at the below program for more clear understanding.

Example

                    

class student:
    name = 'David Alaba'
    age = 25
    city = 'California'
    gender = 'Male'

print(student)
print()

stud = student()

print('Name of the student:', stud.name)
print('Age of the student:', stud.age)
print('City of the student:', stud.city)
print('Gender of the student:', stud.gender)
print()

del stud   # deletes class object
print('Name of the student:', stud.name)

# OR

del student   # deletes the entire class
print(student)

Output

                    

<class '__main__.student'>

Name of the student: David Alaba
Age of the student: 25
City of the student: California
Gender of the student: Male

Traceback (most recent call last):
File "", line 17, in 
NameError: name 'stud' is not defined

Deleting Variables, Lists and Dictionary

Python del statement can also be used to delete different iterables ranging from variables, lists, tuples, dictionaries, set, etc.

Example

                    

name = 'Sammy'
car_list = ['Ford', 'Tata', 'Ferrari', 'BMW', 'Audi']
my_tuple = (1, 'John', 2, 'Riya', 3, 'Sam')
my_dict = {'Name': 'Frank', 'Age': 24, 'City': 'California', 'Gender': 'Male'}

del name
del car_list
del my_tuple
del my_dict

print(name)      # will print NameError: name 'name' is not defined
print(car_list)  # will print NameError: name 'car_list' is not defined
print(my_tuple)  # will print NameError: name 'my_tuple' is not defined
print(my_dict)   # will print NameError: name 'my_dict' is not defined

Output

                    

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

Deleting an Item, Slice from a List

Python del statement can also be used to delete a specific element from the iterable object, or it can also be used to delete a range of data values from the iterables. This can be done by using the Indexing method. Index values need to be specified in order to delete specific data values.

Example

                    

num_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
print('Original List:', num_list)
print()

# deleting 4th value in the list
del num_list[3]
print('Updated List:', num_list)

# deleting values from position 3 to 6
del num_list[3:7]
print('New updated list:', num_list)

# deleting all values of the list
del num_list[:]
print(num_list)

Output

                    

Original List: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]

Updated List: [1, 3, 5, 9, 11, 13, 15, 17, 19, 21, 23, 25]
New updated list: [1, 3, 5, 17, 19, 21, 23, 25]
[]

Note – Single items and values inside the tuple and string cannot be deleted. Tuples and strings are immutable objects, meaning they can’t be modified after they’ve been created. However, we can delete an entire tuple or a string.

Example

                    

my_tuple = (1, 'John', 2, 'Riya', 3, 'Sam')

del my_tuple[2]
print(my_tuple)

Output

                    

Traceback (most recent call last):
File "", line 3, in 
TypeError: 'tuple' object doesn't support item deletion

Remove a key:value pair from a dictionary

In a dictionary, Python del can be used to delete a specific key-value pair. For deleting a specific data element in the dictionary, the del statement only accepts the key as an index value. This can be done using the below method.

Example

                    

employee = {'Name': 'Ayesha', 'Age': 28, 'Gender': 'Female', 
            'Profession': 'Marketing', 'Designation': 'Manager', 
            'Salary': 65000}
print('Dict:', employee)

# del statement only accepts key as index value
del employee['Gender']   # Gender key-value pair will be deleted from the employee dict
print('Updated Dict:', employee)

Output

                    

Dict: {'Name': 'Ayesha', 'Age': 28, 'Gender': 'Female', 'Profession': 'Marketing', 'Designation': 'Manager', 'Salary': 65000}
Updated Dict: {'Name': 'Ayesha', 'Age': 28, 'Profession': 'Marketing', 'Designation': 'Manager', 'Salary': 65000}

Frequently Asked Questions

Q1. What is the use of del in Python?

Python’s del statement is used to delete variables and objects in the Python program. Iterable objects such as user-defined objects, lists, set, tuple, dictionary, variables defined by the user, etc. can be deleted from existence and from the memory locations in Python using the del statement. The 2 reasons for using the del statement are – The first is to remove elements from dicts and lists by index; for lists, you can also delete a slice. The second reason is to unbind a variable. Deleting a variable has no greater impact on memory use than changing the value to None.

Q2. How do you del statements in Python?

To delete a variable or an object in Python, we use the following syntax –

                    

del obj_name[optional]

where,

obj_name = name of the variable, user-defined object, list, tuple, set, dictionary, etc.

[optional] = Index value for slicing/deleting specific data elements from the object iterables.

Example

                    

games = ['cricket', 'football', 'hockey', 'golf', 'chess']

del games[2]
print('Games list:', games)
print()

food = ['burger', 'pizza', 'pattice', 'sandwich']
del food
print(food)

Output

                    

Games list: ['cricket', 'football', 'golf', 'chess']

Traceback (most recent call last):
File "", line 9, in 
NameError: name 'food' is not defined

Q3. What is __del__ in Python?

In Python, the __del__() method is referred to as a destructor method. It is called after an object’s garbage collection occurs, which happens after all references to the item have been destroyed.

Example

                    

# Python program to illustrate __del__
class Student:
       # Initializing
       def __init__(self):
             print('Student table created.')

       # Deleting (Calling destructor)
       def __del__(self):
             print('Destructor called, Student table deleted.')

Stud1 = Student()
del Stud1

Output

                    

Student table created.
Destructor called, Student table deleted.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.