Python List – remove()

Python list.remove(element) method removes the first occurrence of given element from the list.

If specified element is present in the list, remove() method raises ValueError.

If there are multiple occurrences of specified element in the given list, remove() method removes only the first occurrence, but not the other occurrences.

remove() method modifies the original list.

Syntax

The syntax to call remove() method on a list myList is

</>
Copy
myList.remove(element)

where

  • myList is a Python list
  • remove is method name
  • element is the object to be removed from the list

Examples

Remove Element from List where Element occurs only once in the List

In the following program, we initialize a list myList with some elements, and remove the element 'apple' from the list. In this scenario, the element 'apple' occurs only once in the list myList.

main.py

</>
Copy
#take a list
myList = ['apple', 'banana', 'cherry']

#remove 'apple'
myList.remove('apple')

print(f'resulting list : {myList}')

Output

resulting list : ['banana', 'cherry']

Remove Element from List where Element occurs multiple times in the List

In the following program, we initialize a list myList with some elements, and remove the element 'apple' from the list. In this scenario, the element 'apple' occurs thrice in the list myList. remove() method must remove only the first occurrence in the calling list.

main.py

</>
Copy
#take a list
myList = ['apple', 'banana', 'apple', 'apple', 'cherry']

#remove 'apple'
myList.remove('apple')

print(f'resulting list : {myList}')

Output

resulting list : ['banana', 'apple', 'apple', 'cherry']

Remove Element from List where Element is not in the List

In the following program, we initialize a list myList with some elements, and remove the element 'apple' from the list. In this scenario, the element 'apple' is not present in the list myList. remove() method throws ValueError.

main.py

</>
Copy
#take a list
myList = ['banana', 'cherry']

#remove 'apple'
myList.remove('apple')

print(f'resulting list : {myList}')

Output

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    myList.remove('apple')
ValueError: list.remove(x): x not in list

Conclusion

In this Python Tutorial, we learned how to remove the first occurrence of an element from the list using list.remove() method.