Remove () in python

Remove in Python :

Remove is used delete an object from list in python. It does not return any value.

If there are mulitple element/object of same value it will delete first occurance of that element / object from the list.

Example :

  • list=[ 1 , 2, 4 , 5 , 6]
    • list.remove( 2 )
    • list=[ 1, 4 , 5 , 6]
remove in python

Syntax :

  list_name.remove( obj )

 obj - element to be deleted.

Returns Nothing , but remove the element from the list.

Code #1:

#pyhton program 
#remove 

li=[1,2,3,5,6,7,8,2,2,2]

#removing a element 
li.remove(2)
print(li)

Output :

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

Delete the First Occurance of “2” , in the above program.

Code #2:

#pyhton program 
#remove 

li=[1,2,3,5,6,7,8,2,2,2]

#removing every occurance of an element
while(2 in li):
    li.remove(2)
print(li)

Output :

[1, 3, 5, 6, 7, 8]

In the above program , if we want to delete every occurance of “2” we can use a while statement and remove function to do this.

Code #3:

#pyhton program 
#remove 

li=[1,2,3,5,6,7,8,2,2,2]

#removing all elements from list
i=0
while(li):
    li.remove(li[i])
print(li)

Output :

[ ]

If we try to remove a element from the list , which is not in the list it will raise an error ValueError.