Python List Pop Example | pop() Method Tutorial
Python List Pop Example | pop() Method Tutorial is today’s topic. The list pop() method removes the element at the specified position. It returns the deleted item. The Python List pop() method removes and returns the object at the given index (passed as an argument) from a list.
Python List Pop Example
The pop() method takes the single argument as a position, in our case, it is an index and removes the item present at that position from the list. If the index passed to a pop() method is not in the range or does not exist in the list, then it throws IndexError: pop index out of range exception. The parameter passed to the pop() method is optional. If no parameter is passed, the default index -1 is given as an argument which returns the last element.
The syntax for list pop() method is following.
The index parameter is required, and it is the position from where we need to remove the element from the list. Let us take a simple example.
# app.py GoT = ['Daenerys', 'Jon', 'Tyrion'] removedItem = GoT.pop(1) print (removedItem)
The output is following.
List index in Python starts from 0, not 1. So, if you need to pop 2nd element, you need to pass 1 to the pop() method.
Pass the negative index in pop() method
Let’s see the following scenario where we pass the negative index to the pop() method.
# app.py GoT1 = ['Daenerys', 'Jon', 'Tyrion'] removedItem1 = GoT1.pop(-1) print (removedItem1)
In python programming, if we pass the negative index, then it will start from the end of the list. So in the above example, -1 means the last element of the list which is Tyrion. So that element will be removed.
If you need to delete or remove the given item from the list, you need to use list remove() method.
Pass the index which does not exist in List
Take a look at the following scenario where we the index does not exist in the list and see the output.
# app.py GoT2 = ['Daenerys', 'Jon', 'Tyrion'] removedItem2 = GoT2.pop(4) print (removedItem2)
It throws an exception saying IndexError: pop index out of range.
We have seen almost all the possible cases of list pop() method in Python.
Finally, Python List Pop Example | pop() Method Tutorial is over.