The pop() method removes the item at the given index from the list and returns the removed item.
The syntax of the pop``()
method is:
list.pop(index)
pop()
method takes a single argument (index).The pop()
method returns the item present at the given index. This item is also removed from the list.
# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove and return the 4th item
return_value = languages.pop(3)
print('Return Value:', return_value)
# Updated List
print('Updated List:', languages)
Output
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
Note: Index in Python starts from 0, not 1.
If you need to pop the 4th element, you need to pass 3 to the pop()
method.
# programming languages list
languages = ['Python', 'Java', 'C++', 'Ruby', 'C']
# remove and return the last item
print('When index is not passed:')
print('Return Value:', languages.pop())
print('Updated List:', languages)
# remove and return the last item
print('\nWhen -1 is passed:')
print('Return Value:', languages.pop(-1))
print('Updated List:', languages)
# remove and return the third last item
print('\nWhen -3 is passed:')
print('Return Value:', languages.pop(-3))
print('Updated List:', languages)
Output
When index is not passed:
Return Value: C
Updated List: ['Python', 'Java', 'C++', 'Ruby']
When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']
If you need to remove the given item from the list, you can to use the remove() method.
#python