The remove()
method is a built-in method in Python that removes a specified element in a list. If the specified element is present more than once, its first occurrence is removed from the list.
The syntax of the remove()
method is as follows.
list.remove(element)
This method takes one necessary parameter that needs to be removed from the list.
The remove()
method does not return a value. However, if the specified element is not present in a list, it gives a value error.
In the code below, the element e
is removed from the list vowels
. In the next attempt to remove s
from the list, the function gives a value error because s
is not present in the vowels
list.
# vowels listvowels = ['a', 'e', 'i', 'o', 'u']# 'e' is removed by remove() funtionvowels.remove('e')# Updated vowels Listprint('Vowels list: ', vowels)# 's' ihas to be removed from vowels: Value errorvowels.remove('s')print('Error Vowels list: ', vowels)
In the number
list, 6
is present twice and the remove()
function removes its first instance.
# number listnumber = [1, 2, 3, 6, 4, 5, 6]# '6' is removed by remove() funtionnumber.remove(6)# Updated number Listprint('Number list: ', number)