Python list remove() – GeeksforGeeks

Python List remove() is an inbuilt function in the Python programming language that removes a given object from the List. 

Syntax: 

list_name.remove(obj) 

Parameters:  

  • obj: object to be removed from the list 

Returns:  

The method does not return any value but removes the given object from the list.

Exception:

If the element doesn’t exist, it throws ValueError: list.remove(x): x not in list exception.

Note: 

It removes the first occurrence of the object from the list. 

Example 1: Remove element from the list  

Python3




 

list1 = [ 1, 2, 1, 1, 4, 5 ]

list1.remove(1)

print(list1)

 

list2 = [ 'a', 'b', 'c', 'd' ]

list2.remove('a')

print(list2)



Output

[2, 1, 1, 4, 5]
['b', 'c', 'd']

Example 2: Deleting element that doesn’t exist  

Python3




 

 

list2 = [ 'a', 'b', 'c', 'd' ]

 

list2.remove('e')

print(list2)



Output: 

Traceback (most recent call last):
  File "/home/e35b642d8d5c06d24e9b31c7e7b9a7fa.py", line 8, in 
    list2.remove('e') 
ValueError: list.remove(x): x not in list

Example 3: Using remove() Method On a List having Duplicate Elements  

Python3




list2 = [ 'a', 'b', 'c', 'd', 'd', 'e', 'd' ]

 

list2.remove('d')

 

print(list2)



Output

['a', 'b', 'c', 'd', 'e', 'd']

Note: If a list contains duplicate elements, it removes the first occurrence of the object from the list. 

Example 4: Given a list, remove all the 1’s from the list and print the list

Python3




  

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]

 

while (list1.count(1)):

    list1.remove(1)

     

print(list1)



Output

[2, 3, 4, 4, 5]

Example 5: Given a list, remove all the 2’s from the list using in keyword 

Python3




 

mylist = [1, 2, 3, 2, 2]

 

while 2 in mylist:

    mylist.remove(2)

 

print(mylist)



Output

[1, 3]

Complexity Class:  

  • Average case : O(N)
  • Amortised Worst case : O(N)

My Personal Notes

arrow_drop_up