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

Stack

Popping 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

  1. Check that the stack is not empty — length 0 must raise underflow, not return a stale value.
  2. Read the value at index length - 1 (3 in the default stack [1, 2, 3]).
  3. Shrink the stack by one so that slot is no longer reachable.
  4. Update the 'top' reference to the element beneath, now index 1.
  5. Return the removed value to the caller.

Pop Worked Example

Input: pop() on the default stack [1, 2, 3]

  1. Top item is 3 at index 2.
  2. Remove it — the stack becomes [1, 2].
  3. New top is 2, so a second pop() would return 2, then 1, then raise underflow.

Output: Popped value: 3, remaining stack: [1, 2]

Try your own input
Stack: PopO(1)
Removes and returns the value currently on top of the stack.
bottom
1
2
3
← top
Active / highlighted Min stack Result
Stack: Pop
Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
stack = [1, 2, 3]
top = stack.pop()  # removes and returns 20
print(top, stack)  # 20 [10]
# example: pop on [1, 2, 3]
Input: pop() on the default stack [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

TimeO(1)
SpaceO(1) per operation

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.