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.
In [1]:
l = [1, 2, 3, 4]
In [2]:
l[1] = 11
In [3]:
l
Out[3]:
[1, 11, 3, 4]
In [4]:
l = [1, 2, 3, 4, 4, 6]
In [5]:
l.remove?
Signature: l.remove(value, /) Docstring: Remove first occurrence of value. Raises ValueError if the value is not present. Type: builtin_function_or_method
In [6]:
l.remove(4)
In [7]:
l
Out[7]:
[1, 2, 3, 4, 6]
In [8]:
l.pop?
Signature: l.pop(index=-1, /) Docstring: 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
In [9]:
l.pop()
Out[9]:
6
In [10]:
l
Out[10]:
[1, 2, 3, 4]
In [11]:
l.pop(2)
Out[11]:
3
In [12]:
l
Out[12]:
[1, 2, 4]
In [13]:
l.clear()
In [14]:
l
Out[14]:
[]