list · Python
pop
Removes and returns the element at i (default: the last one).
list.pop(i=-1, /)
Complexity
| Best case | O(1) for pop() |
|---|---|
| Worst case | O(n) for pop(0) |
| Extra space | O(1) |
Removing the last element moves nothing; removing at i shifts len − i − 1 pointers left.
Tested example
items = [5, 6, 7, 8]
assert items.pop() == 8 # last element: O(1)
assert items.pop(0) == 5 # first element: shifts the rest, O(n)
assert items == [6, 7]
try:
[].pop()
raise AssertionError("expected IndexError")
except IndexError:
pass
Parameters
- i
- Position; default -1 (the last element).
Behaviour
- Returns
- The removed element.
- Errors and preconditions
- IndexError if the list is empty or i is out of range.
- Changes
- The list shrinks by 1; may release spare capacity.
- Memory and invalidation
- CPython shrinks the allocation when the list falls below half of it.