Removes an item from a list and returns it.
Synopsis
items.pop()
items.pop(index)
Description
Without an index, pop removes the last item. With an index, it removes the item at that position.
Parameters
| Name | Meaning |
|---|---|
index |
Which position to remove. Optional. The default is the last item. |
Return value
The item that was removed.
Example
stack = ["a", "b", "c"]
last = stack.pop()
print(last)
print(stack)
first = stack.pop(0)
print(first, stack)
It prints:
c
['a', 'b']
a ['b']
Common mistake
items = []
items.pop()
Python stops with:
IndexError: pop from empty list
An empty list has nothing to remove. Check if items: first.
See also
Last updated 2 weeks ago