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, undoA 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
| Action | Stack from bottom to top | Result |
|---|---|---|
| Start | empty | No top item |
| Push A | A | A is on top |
| Push B | A, B | B is on top |
| Peek | A, B | See B without removing it |
| Pop | A | Remove 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.
