Summary: In this tutorial, we will learn to delete the last item from the Python list using the list.pop() method.

The list.pop([i]) is another built-in method in Python that removes the item at the index position i from the list object.

For example, in the following list, the list.pop method removes the item at the index 1 (i.e., second item):

>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(1)
'b'
>>> print(l)
['a', 'c', 'd']

If we don’t specify the index value then the pop method by default removes the last item from the list.

>>> l = [1, 2, 3, 4]
>>> l.pop()
4
>>> print(l)
[1, 2, 3]

Parameters and Return Value

The list.pop([i]) method accepts one optional argument that is the index of the item i that needs to be removed from the list.

It returns the item that it deletes from the list.

The square brackets around the i in the method signature denote that the parameter is optional.

Python docs

Examples using list.pop()

Example 1: Remove the last element from the list using the list.pop() method

>>> l = ['Python', 'C++', 'Java', 'R']
>>> l.pop()
'R'
>>> print(l)
['Python', 'C++', 'Java']

Example 2: Remove the first item from the list data structure using the list.pop(i) method

>>> l = ['Python', 'C++', 'Java', 'R']
>>> l.pop(0)
'Python'
>>> print(l)
['C++', 'Java', 'R']

Example 3: Remove the item at index i using the list.pop(i) method

>>> l = [25, 5, 33, 11, 2, 9]
>>> l.pop(2)
33
>>> print(l)
[25, 5, 11, 2, 9]

Example 4: Remove the item from the list on the basis of negative index using the pop method

>>> l = [1, 2, 3, 4, 5]
>>> l.pop(-1)
5
>>> print(l)
[1, 2, 3, 4]

Conclusion

The list.pop() method is a built-in list method that deletes the item at the specified index from the list.

If we don’t specify the index position then the list.pop() method removes the last item from the given list.

Leave a Reply