list.pop()
Python · Lists
Theory
.pop() removes the last item of a list and returns it, so you can remove and use a value in one step. sales = [100, 250, 300] then last = sales.pop() leaves last = 300 and sales = [100, 250]. Pass an index to remove a specific position instead: sales.pop(0) removes and returns the first item. Calling pop() on an empty list, or with an index that does not exist, raises IndexError.
Popping from the end is O(1), since nothing has to move, which makes append() plus pop() a perfect stack: last in, first out, like a pile of plates or an undo history. Popping from the front, pop(0), is O(n) because all remaining items shift left; for a first-in, first-out queue use collections.deque and its popleft(). Unlike remove(), pop() works by position, and unlike del, it gives you the removed value back.
Why we use it
Many algorithms process items one at a time while taking them out of a collection: undo stacks, depth-first search, work lists. pop() removes the item and hands it to you in a single step.
When to use it
Use pop() to take the last item (stack behaviour) or pop(i) when you need the value at a position. Use del list[i] if you do not need the value, remove() to delete by value, and deque.popleft() for queues.
How it works
- Call sales.pop()
- Is the list empty? Yes: Raise IndexError. No: Take the item at the last index.
- Remove that slot and shrink the list by 1
- Return the removed item to the caller
- print(last, sales) shows 300 [100, 250]
Syntax
list.pop()
list.pop(index)Example
sales = [100, 250, 300]
last = sales.pop()
print(last, sales)Key points
- With no argument, removes and returns the last item
- pop(i) removes and returns the item at index i
- Raises IndexError on an empty list
- pop() from the end is O(1); pop(0) is O(n)
- Useful for implementing a stack (last-in, first-out)