Reading preferences
Concept

Stacks

Add and remove from the same end, like a stack of plates, and understand when last-in-first-out helps.

stack, lifo, push, pop, peek, undo

A pile of plates

Imagine a pile of plates. You add a plate at the top, and take a plate from the top. If A goes on first and B goes on next, B comes off first.

A stack follows that rule: last in, first out, or LIFO. The accessible end is called the top.

Push A      Push B        Pop B
 top         top            top
 [A]         [B]            [A]
             [A]

The diagram shows the top above the bottom. The letter B is the most recently added item, not the alphabetically greatest item.

Why we need it and where it is used

Sometimes we must return to the most recent unfinished thing first. A text editor can use a stack of recorded actions to help undo recent changes. Programs can also use stacks to keep track of unfinished work while exploring nested structures.

A stack describes an access rule, not one particular storage layout. We can implement it with an array-like list or with linked nodes. It does not automatically implement undo; the program must record enough information and choose how to reverse each action.

Follow push, peek, and pop

ActionStack from bottom to topResult
StartemptyNo top item
Push AAA is on top
Push BA, BB is on top
PeekA, BSee B without removing it
PopARemove and return B

Push adds an item; pop removes and returns the top item. Peek looks at the top without removing it. An empty stack has no item to peek or pop.

See the reasoning

Follow the example one step at a time

Follow a last-in, first-out stack. This is a prepared teaching demonstration, not live code execution.

Start empty

bottom [ ] top

There is no top item yet.

Python illustration

stack = []
stack.append("A")
stack.append("B")
print("peek:", stack[-1])
print("pop:", stack.pop())
print("pop:", stack.pop())
print("empty:", len(stack) == 0)

Prepared output — not live execution:

peek: B
pop: B
pop: A
empty: True

We use the end of a Python list as the top. stack[-1] looks at the last item; pop() removes it. Either operation raises IndexError on an empty list, so check whether an item exists or handle the exception when needed.

Time, space, and common mistakes

Reading the top of a Python list is O(1). For a resizable array-backed list, end pushes and pops are O(1) amortised across operations; a resize can occasionally take O(n). Storing n items uses O(n) space.

Do not remove from the front and call it a stack: that changes the ordering. If the oldest item should come out first, learn about a queue.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Push A, then B, onto an empty stack. Which item does pop remove first?
2. What does peek do?
3. What happens when Python list.pop() is called on an empty list?
4. Why can a stack help with undoing recent changes?

References and further reading