Quick Reach
Remove method to remove objects from list
The remove() method is used to remove an object or element from list. If there are multiple occurrences of object specified in remove() method then only first object/element will be removed.
Syntax of remove() method
List_name.remove(object/element)
Where object or element is the list item to be removed from the list.
Example of using remove() method
In example below a list is created with mixed numbers and strings. We will use list remove method and remove numbers one by one and then print the final list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# This is remove method example
list_Py = [1, ‘this’, 2, ‘is’, 3, ‘list’, 4, ‘chapter’]
print (list_Py)
list_Py.remove(1)
list_Py.remove(2)
list_Py.remove(3)
list_Py.remove(4)
print (list_Py)
|
Output will be:
[1, ‘this’, 2, ‘is’, 3, ‘list’, 4, ‘chapter’]
[‘this’, ‘is’, ‘list’, ‘chapter’]
Using del statement to remove elements
If you exactly know the order of list then del statement can be used to remove element from list as below. Just to remind index of list start from 0.
Example of using del method
1
2
3
4
5
6
7
8
9
|
# This is del method example
list_Py = [‘this’,‘is’,‘list’,‘chapter’]
print (“List before delete:”, list_Py)
del list_Py[0]
print (“List after delete:”,list_Py)
|
Output will be
List before delete: [‘this’, ‘is’, ‘list’, ‘chapter’]
List after delete: [‘is’, ‘list’, ‘chapter’]
Leave A Comment?