
In this post, you will learn How to delete an item from list using pop method.
Pop in Python –
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.
Syntax of pop –
list.pop(index)
The pop method takes a single argument, the index of the item that you want to remove. If you do not pass the index then pop will delete the last item from the list.
Pop Item without an index –
This will remove the last item from the list
In [8]: companies = ['Google','Apple','Microsoft','Netflix', 'Facebook']
In [9]: last_item = companies.pop()
In [10]: last_item
Out[10]: 'Facebook'
Pop item with an Index –
Remove the second item from the list
In [11]: companies
Out[11]: ['Google', 'Apple', 'Microsoft', 'Netflix']
In [12]: second = companies.pop(1)
In [13]: second
Out[13]: 'Apple'
Pop Item with Negative indexing –
Remove the second last item from the list.
In [14]: companies
Out[14]: ['Google', 'Microsoft', 'Netflix']
In [15]: second_last = companies.pop(-2)
In [16]: second_last
Out[16]: 'Microsoft'