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
#- list.append()Adds one item to the end of a list.
- list.remove()Removes the first occurrence of a given value from a list.
- list.insert()Inserts an item at a chosen position in a list.
- list.clear()Removes all the items from a list.
- collections.dequeA double-ended queue: fast adding and removing of items at both ends, optionally with a length limit.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.