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 –
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 : companies = ['Google','Apple','Microsoft','Netflix', 'Facebook'] In : last_item = companies.pop() In : last_item Out: 'Facebook'
Pop item with an Index –
Remove the second item from the list
In : companies Out: ['Google', 'Apple', 'Microsoft', 'Netflix'] In : second = companies.pop(1) In : second Out: 'Apple'
Pop Item with Negative indexing –
Remove the second last item from the list.
In : companies Out: ['Google', 'Microsoft', 'Netflix'] In : second_last = companies.pop(-2) In : second_last Out: 'Microsoft'