Python list.remove() function


The list.remove() method in Python is used to remove the first occurrence of a specified element from a list. If the element is not found, it raises a ValueError. This method modifies the original list in place and does not return a new list.

Syntax

list.remove(element)
  • Parameters:
    • element: The item to be removed from the list. This can be any data type present in the list.

Return Value

  • The method does not return a value (None is returned implicitly).

Example Usage

  1. Removing an Element from a List:

    my_list = [1, 2, 3, 4] my_list.remove(3) # Removes the first occurrence of 3 print(my_list) # Output: [1, 2, 4]
  2. Removing a String Element:

    my_list = ['apple', 'banana', 'cherry'] my_list.remove('banana') # Removes 'banana' print(my_list) # Output: ['apple', 'cherry']
  3. Removing an Element Not in the List: If you try to remove an element that is not in the list, a ValueError will be raised:

    try: my_list.remove('orange') # Attempting to remove 'orange', which is not in the list except ValueError as e: print(e) # Output: list.remove(x): x not in list
  4. Removing the First Occurrence: If there are multiple occurrences of an element, remove() will only delete the first one:

    my_list = [1, 2, 3, 2, 4] my_list.remove(2) # Removes the first occurrence of 2 print(my_list) # Output: [1, 3, 2, 4]
  5. Removing an Element from an Empty List: Attempting to remove an element from an empty list will also raise a ValueError:

    empty_list = [] try: empty_list.remove(1) # Attempting to remove from an empty list except ValueError as e: print(e) # Output: list.remove(x): x not in list

Summary

  • list.remove(element) is a useful method for removing the first occurrence of an item from a list.
  • It modifies the original list in place, making it an efficient way to manage list contents.
  • It raises a ValueError if the specified element is not found, so it's important to ensure that the element exists in the list before calling this method.