PythonLists and tuples
list. pop()
Removes the item at the given index (the last one by default) and returns it.
- Returns
- The removed item.
- Changes the original
- Yes
Example
#Python
history = ["step 1", "step 2", "step 3"]
last = history.pop()
first = history.pop(0)
print(last)
print(first)
print(history)Resultsaved result, you can check it
step 3
step 1
['step 2']
Definition and usage
#The pop() method with no argument removes and returns the last item of the list. With an index, it removes the item at a specific position, for example pop(0) takes the first one.
On an empty list, or with an index out of range, it raises an IndexError.
The pair append() and pop() lets you use a list as a stack: the last item added comes out first. pop(0) is slow on large lists, so collections.deque is a better choice for queues.
Syntax
#Syntax
list.pop()
list.pop(index)Parameters
#index
int, default -1
The position of the item to remove.
More examples
#Python
empty = []
try:
empty.pop()
except IndexError as error:
print(error)Resultsaved result, you can check it
pop from empty list
Good practices
#- Before calling
pop()on a list that might be empty, checkif my_list:. - For queues (adding at the end, removing from the start), use
collections.deque.
Related entries
#Spotted a mistake or missing an example? Write to us.