Python List | pop method
Start your free 7-days trial now!
Python's list.pop(~)
method removes the element at the given index from a list and then returns the removed value.
The list.pop(~)
method is useful when you want to remove an element from a list and then perform some action with the removed element such as adding it to another list.
Parameters
1. index
| number
| optional
The index position of the element to be removed. Default is -1
, the last element in the list.
Return value
The removed value.
Examples
Basic usage
To remove the last element of fav_animals
and return it:
fav_animals = ['cat', 'doge', 'bird']fav_animals.pop()
'bird'
To pop the first element of fav_animals
and add it to a separate list norm_animals
:
fav_animals = ['cat', 'doge', 'bird']norm_animals = []norm_animals.append(fav_animals.pop(0))print("fav_animals =", fav_animals)print("norm_animals =", norm_animals)
fav_animals = ['doge', 'bird']norm_animals = ['cat']
Here 'cat'
is popped from fav_animals
and then used as input for the list.append(~)
method to add it to the list norm_animals
.
IndexError
If the specified index to pop does not exist, an IndexError
is raised:
fav_animals = ['cat', 'doge', 'bird']fav_animals.pop(3)
IndexError: pop index out of range