Updating and Deleting Elements - list

Here is how we can update elements in the list as well as delete elements from the list in Python.

  • We can assign an element to the list using index to update.

  • There are multiple functions to delete elements from list.

    • remove - delete the first occurrence of the element from the list.

    • pop - delete the element from the list using index.

    • clear - deletes all the elements from the list.

l = [1, 2, 3, 4]
l[1] = 11
l
[1, 11, 3, 4]
l = [1, 2, 3, 4, 4, 6]
l.remove?
Docstring:
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
Type:      builtin_function_or_method
l.remove(4)
l
[1, 2, 3, 4, 6]
l.pop?
Docstring:
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
Type:      builtin_function_or_method
l.pop()
6
l
[1, 2, 3, 4]
l.pop(2)
3
l
[1, 2, 4]
l.clear()
l
[]