Removing Elements in a List
There are three ways in which you can Remove elements from List:
-
Using the
remove()method -
Using the list object’s
pop()method -
Using the
deloperator -
We can also remove elements from a list by assigning the empty list to them:
alist = ['a', 'b', 'c', 'd', 'e', 'f']
alist[1:3] = []
print(alist)
['a', 'd', 'e', 'f']
1. Remove() Method
When using this method, you will need to specify the particular item that is to be removed from the list.
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
['a', 'c']
This is a slow technique, as it involves searching the item in the list.
2. pop() Method
This method removes an item or an element from the list, and returns it.
When using the pop(), we specify the index of the item as the argument.
This 'pops' out the item to be returned at the specified index. If the particular item to be removed is not found, then an IndexError is raised.
Example:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b
3. del Operator
The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned.
The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned.
The operator also supports removing a range of items in the list using the but will raises an IndexError, when the index or the indices specified are out of range.
Example:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']