Data Structures · Visualization
Stack: Pop
Stack
Popping removes and returns the item currently on top of the stack. Time: O(1). Space: O(1) per operation.
Big-O: push / pop / peek are all O(1).
Stack: Pop
StackPopping removes and returns the item currently on top of the stack. The visualizer shows it on the default stack [1, 2, 3], where pop() takes 3 first and leaves [1, 2] with 2 as the new top. Because the operation only ever touches the last slot, nothing shifts and the cost stays O(1); the one case worth defending is an empty stack, where pop is undefined and implementations raise 'stack underflow' rather than reading garbage memory.
How Pop Works
- Check that the stack is not empty — length 0 must raise underflow, not return a stale value.
- Read the value at index length - 1 (3 in the default stack [1, 2, 3]).
- Shrink the stack by one so that slot is no longer reachable.
- Update the 'top' reference to the element beneath, now index 1.
- Return the removed value to the caller.
Pop Worked Example
Input: pop() on the default stack [1, 2, 3]
- Top item is 3 at index 2.
- Remove it — the stack becomes [1, 2].
- New top is 2, so a second pop() would return 2, then 1, then raise underflow.
Output: Popped value: 3, remaining stack: [1, 2]
Press ▶ Run to watch it step by step.
stack = [1, 2, 3]
top = stack.pop() # removes and returns 20
print(top, stack) # 20 [10]
# example: pop on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Pop Time & Space Complexity
When to Use Pop
- Returning from a function call (popping the call stack)
- Undoing the most recent action
- Matching and removing a closing bracket in validation
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.