Python program to remove an element from a list using ‘del’ statement

Python 3 program to remove an element from a list using ‘del’ statement :

In python, we have ‘del’ statement to remove one or multiple elements from a list. In this example, we will learn different uses of ‘del’ statement. Let’s take a look :

Delete a single element from a list :

Using ‘del’ statement, we can delete one single element from a list by using its index. If the name of the list is ‘list’ and if we want to remove an element in position ‘ i’, we can use ‘del list[i]’. Index starts from ‘0’. Example :

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

print(my_list)

del my_list[5]

print(my_list)

Output :

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

So, we have removed the element in 5th position, i.e. ‘6’.

Delete multiple elements from a list :

Using ‘del’ statement, we can delete elements within a range. e.g., ‘del list[min_range:max_range]’ will delete elements of the list from index position ‘min_range’ to ‘max_range – 1’. Example :

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

print(my_list)

del my_list[2:5]

print(my_list)

Output :

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

The above program removes the elements from index number 2 to index 4.

Deleting all elements from a list :

To delete all elements of a list, we can use ‘del list_name[:]’. Example :

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

print(my_list)

del my_list[:]

print(my_list)

Output :

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

So, all the elements of the list are removed ‘del my_list[:]’.

Remove list variable using ‘del’ :

We can also remove a variable using ‘del’. ‘del list_name’ to remove list variable with name ‘list_name’. Example :

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

print(my_list)

del my_list

print(my_list)

It will result NameError, as the variable is deleted.

NameError: name 'my_list' is not defined

Leave a Reply