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]
Copy to clipboard
l[1] = 11
Copy to clipboard
l
Copy to clipboard
[1, 11, 3, 4]
Copy to clipboard
l = [1, 2, 3, 4, 4, 6]
Copy to clipboard
l.remove?
Copy to clipboard
Docstring:
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
Type:      builtin_function_or_method
Copy to clipboard
l.remove(4)
Copy to clipboard
l
Copy to clipboard
[1, 2, 3, 4, 6]
Copy to clipboard
l.pop?
Copy to clipboard
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
Copy to clipboard
l.pop()
Copy to clipboard
6
Copy to clipboard
l
Copy to clipboard
[1, 2, 3, 4]
Copy to clipboard
l.pop(2)
Copy to clipboard
3
Copy to clipboard
l
Copy to clipboard
[1, 2, 4]
Copy to clipboard
l.clear()
Copy to clipboard
l
Copy to clipboard
[]
Copy to clipboard