
Problem –
You want to remove an element from a list by index in Python.
Solution –
Using del –
If you know the position of an item in a list, you can remove it using del statement.
In [2]: companies = ['Google','Apple','Microsoft','Netflix', 'Facebook']
Let’s say you want to delete the first item from the list.
In [3]: del companies[0]
In [4]: companies
Out[4]: ['Apple', 'Microsoft', 'Netflix', 'Facebook']
You can remove any item from the list using del statement if you know the index of the item in the list.
To delete the last item from the list.
In [5]: del companies[-1]
In [6]: companies
Out[6]: ['Apple', 'Microsoft', 'Netflix']
Once you delete an item from a list using del statement you can not access that item again.
Using pop –
Sometimes you’ll want to use the value of an item after you remove it from a
list. For this you can use the pop in python. The pop method removes an item from the list at a given position or index and return the removed item.
In [1]: companies = ['Google', 'Apple', 'Microsoft', 'Netflix', 'Facebook']
In [2]: # remove the 2nd element from the list
In [3]: second = companies.pop(1)
In [4]: second
Out[4]: 'Apple'
If No index is provided then by default pop will remove the last item from the list.
In [5]: last = companies.pop()
In [6]: last
Out[6]: 'Facebook'
You can also use negative index. Let’s delete the second last element from the list.
In [7]: companies
Out[7]: ['Google', 'Microsoft', 'Netflix']
In [8]: second_last = companies.pop(-2)
In [9]: second_last
Out[9]: 'Microsoft'