Python List pop() - Return and Remove Element
The pop()
method returns an item from the specified position in the list and removes it.
If no index is specified, the pop()
method removes and returns the last item in the list.
Syntax:
list.pop(index)
Parameters:
index: (Optional) The element at the specified index is removed. If the index is not specified, the last element is removed.
Return Value:
A list item.
The following example demonstrates the pop()
method.
cities = ['Mumbai', 'London', 'Paris', 'New York']
print(cities.pop()) # returns and removes 'New York'
print('List Elements: ', cities)
print(cities.pop()) # returns and removes 'Paris'
print(cities)
print(cities.pop()) # returns and removes 'London'
print(cities)
print(cities.pop()) # returns and removes'Mumbai'
print(cities)
# cities.pop() # raise an error on an empty list
New York
List Elements: ['Mumbai', 'London', 'Paris']
Paris
List Elements: ['Mumbai', 'London']
London
List Elements: ['Mumbai']
Mumbai
List Elements: []
In the above example, each call of cities.pop()
will return the last element in the list and also removes it.
Calling the pop()
method on an empty list will raise an error.
You can specify an index of an item to be returned and removed from a list.
cities = ['Mumbai', 'London', 'Paris', 'New York']
city = cities.pop(0)
print(city)
print("List Elements: ",cities)
city = cities.pop(2)
print(city)
print("List Elements: ",cities)
Mumbai
List Elements: ['London', 'Paris', 'New York']
New York
List Elements: ['London', 'Paris']
In the above example, cities.pop(0)
returns the first element and removes it.
cities.pop(2)
returns and removes element from the 2nd index.
The pop()
method will throw an IndexError
if the specified index is not found.
cities = ['Mumbai', 'London', 'Paris', 'New York']
city = cities.pop(5)
Traceback (most recent call last):
cities.pop(5)
IndexError: pop index out of range