Python List pop()

The pop() method removes the item at the given index from the list. The method also returns the removed item.

The syntax of the pop() method is:

list.pop(index)

pop() parameter

The pop() method takes a single argument (index) and removes the item present at that index.

If the index passed to the pop() method is not in range, 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 passed as an argument which returns the last item.


Return Value from pop()

The pop() method returns the item present at the given index. This item will be removed the list.


Example 1: Print Element Present at the Given Index from the List

# programming language list
language = ['Python', 'Java', 'C++', 'French', 'C']

# Return value from pop()
# When 3 is passed
return_value = language.pop(3)
print('Return Value: ', return_value)

# Updated List
print('Updated List: ', language)

When you run the program, the output will be:

Return Value:  French
Updated List:  ['Python', 'Java', 'C++', 'C']

It is important to note that the index in Python starts from 0, not 1.

So, if you need to pop 4th element, you need to pass 3 to the pop() method.


Example 2: pop() without an index, and for negative indices

# programming language list
language = ['Python', 'Java', 'C++', 'Ruby', 'C']

# When index is not passed
print('When index is not passed:') 
print('Return Value: ', language.pop())
print('Updated List: ', language)

# When -1 is passed
# Pops Last Element
print('\nWhen -1 is passed:') 
print('Return Value: ', language.pop(-1))
print('Updated List: ', language)

# When -3 is passed
# Pops Third Last Element
print('\nWhen -3 is passed:') 
print('Return Value: ', language.pop(-3))
print('Updated List: ', language)

When you run the program, the output will be:

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.

And, you can use del statement to remove an item or slices from the list.