Manipulating lists in Python using del and remove()

The del statement:

  • It is a versatile way to remove elements from a list based on indices or slices.
  • It can remove a specific element at a given index or delete a range of elements defined by the start and end indices.
  • For example, del list[2] removes the element at index 2, and del list[1:4] removes elements from index 1 to 3. This statement modifies the original list in place.
  • Syntax: del list[start: end]

Note that in the range 1:3, the elements are counted up to 2 and not 3.

remove()` method:

  • This method is specifically designed to eliminate the first occurrence of a particular value in the list.
  • It searches for the provided element and removes it, but it does not rely on indices.
  • If the element appears multiple times, only the first occurrence is removed.
  • If the element is not found, a ValueError is raised.
  • Syntax: list.remove(element)