Python List remove() Method



The Python List remove() Method searches for the given element in the list and removes the first matching element.

For example, consider a list containing fruit names: ['apple', 'banana', 'orange', 'guava', 'banana']. If we call the remove() method on this list to remove the 'banana' duplicate, the first occurrence will be removed and the updated list would be ['apple', 'orange', 'guava', 'banana'].

If the element to be removed is not present in the list, the method raises a ValueError.

Syntax

Following is the syntax for the Python List remove() method −

list.remove(obj)

Parameters

  • obj − This is the object to be removed from the list.

Return Value

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

Example

The following example shows the usage of the Python List remove() method. In here, we are creating a list [123, 'xyz', 'zara', 'abc', 'xyz'] and trying to remove the elements 'xyz' and 'abc' from this list using this method.

aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.remove('xyz')
print("List : ", aList)
aList.remove('abc')
print("List : ", aList)

When we run above program, it produces following result −

List :  [123, 'zara', 'abc', 'xyz']
List :  [123, 'zara', 'xyz']

Example

But as we discussed above, if the object is not present in the list created, a ValueError is raised. Let us see an example demonstrating the same below.

aList = [1, 2, 3, 4]
print("Element Removed : ", aList.remove(5))
print("Updated List:")
print(aList)

Let us compile and run the program, the output is produced as follows −

Traceback (most recent call last):
  File "main.py", line 2, in 
    print("Element Removed : ", aList.remove(5))
ValueError: list.remove(x): x not in list

Example

This method can also remove the None values from the list.

In this example, we are creating a list containing 'None' values. Then, using the remove() method, we are trying to remove the first occurrence of these values from the list. If there are multiple None values, the method can be called multiple times until all of them are removed.

aList = [1, 2, 3, 4, None]
print("Element Removed : ", aList.remove(None))
print("Updated List:")
print(aList)

Let us compile and run the given program to produce the following result −

Element Removed :  None
Updated List:
[1, 2, 3, 4]
python_lists.htm
Advertisements