Python Reference ยท Lists, Tuples and Ranges
Python list.pop() method
Reference for Python list.pop(): remove and return the last item or the item at an index, IndexError on empty lists, stack and queue use, and performance notes.
The pop() method removes an item from a list and returns it. Without an argument it takes the last item, which makes a list work as a stack together with append(). With an index it removes the item at that position.
Because it returns the removed value, pop() is the right tool when you still need that value. If you only want to delete, del items[i] says so more directly.
stack = [1, 2, 3] print(stack.pop()) # 3 print(stack) # [1, 2]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.pop() list.pop(index)
| Name | Description |
|---|---|
index |
Optional. Position of the item to remove. Defaults to -1, the last item. Negative values count from the end. |
Return value: the removed item.
Raises: IndexError if the list is empty or the index is out of range. TypeError if the index is not an integer.
Usage notes
- Last item is fast.
pop()andpop(-1)are O(1).pop(0)and other positions near the front must shift the remaining items, which is O(n). - Queues. For first-in, first-out use
collections.dequeandpopleft(), which is O(1), instead ofpop(0)on a big list. - Empty list raises. Guard with
if items:or catchIndexError. The error message reads "pop from empty list" for an empty list and "pop index out of range" otherwise. - Removing several items. Indexes shift after each pop, so remove from the highest index down, as in the last example, or filter with a comprehension.
- By value, not position. Use
remove()when you know the value but not the index. - Do not pop while iterating the same list with a
forloop; the loop skips items. Iterate over a copy or build a new list. - Other types.
dict.pop(key, default),set.pop()(arbitrary item) andbytearray.pop()exist but have different rules;tupleandstrhave nopop()because they are immutable.