The pop() function in python helps to remove the element from the given index of the list. It also returns that removed element as its output. If the index is not specified, the last element is removed and return.
list.pop(index) #where index must be a integer number
The pop() function takes a single parameter. If the index parameter is not passed, it takes the default index as -1. Which means the index of the last element.
Parameter | Description | Required / Optional |
---|---|---|
index | index of the object to be removed from the list. | Optional |
If the passed index is not in range, it throws IndexError: pop index out of range exception. For returning the 3rd element, we need to pass 2 as an index because the indexing starts from zero.
Input | Return Value |
---|---|
if index | Returns element from the index |
no index | Returns the last element |
# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'f']
# remove and return the 5th item
return_value = alphabets.pop(4)
print('Return element:', return_value)
# Updated List
print('Updated List:', alphabets)
Output:
Return element: e Updated List: ['a', 'b', 'c', 'd', 'f']
# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'f']
# remove and return the last item
print('When index is not passed:')
print('Return element:', alphabets.pop())
print('Updated List:', alphabets)
# remove and return the last item
print('\nWhen -1 is passed:')
print('Return element:', alphabets.pop(-1))
print('Updated List:', alphabets)
# remove and return the fourth last item
print('\nWhen -4 is passed:')
print('Return element:', alphabets.pop(-4))
print('Updated List:', alphabets)
Output:
When index is not passed: Return element: f Updated List: ['a', 'b', 'c', 'd', 'e'] When -1 is passed: Return element: e Updated List: ['a', 'b', 'c', 'd'] When -4 is passed: Return element: a Updated List: ['b', 'c', 'd']