Remove () in python
Remove in Python :
Remove () is a method which is used delete an object from list in python. It does not return any value. If there are multiple element/object of same value it will delete first occurance of that element / object from the list.
remove() in Python:
In Python, we can remove elements from data structures like list, tuple, dictionary and sets using remove function.
Example :
- list=[ 1 , 2, 4 , 5 , 6]
- list.remove( 2 )
- list=[ 1, 4 , 5 , 6]
Syntax :
list_name.remove( obj )
obj – element to be deleted.
Returns Nothing , but remove the element from the list.
Code 1:
#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:
#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:
#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.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment