B2.2.3 Stacks: last in, first out
SL + HLCommand term: Explain1. The returns trolley: last in, first out
Returned books are piled on a trolley. The librarian can only take the book on top. Step through the four stack operations and watch the Python list underneath: the top of the stack is the end of the list.
2. Stack machine: list-based or fixed array?
Operate a stack yourself. Switch the implementation to compare a dynamic Python list with a fixed-size array plus a top index, and see overflow, underflow, cost and memory.
-3. ShelfWise Undo and Redo
Each librarian action is pushed onto the undo stack. Undo pops the most recent action and reverses it, pushing it onto a redo stack. A new action clears the redo stack, as in any editor.
4. Bracket checker: a classic stack algorithm
Python itself uses a stack to check that brackets match. Each opener is pushed; each closer must match the opener on top. Type code or pick an example, then step through.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Stack, queue or list?
Which structure suits the problem best? (Queues, first in first out, come in B2.2.4.) Streaks of 3+ score double.
7. 45-second speed round: trace the stack
A new sequence each time. What is the answer?
Expected output
Think about it
(1) Why must the top of the stack be the end of the list, not the start? (2) Undoing "delete Emma" puts Emma back at the end, not in her old position. What extra data could the action record store to fix that? (3) An undo history that is never cleared keeps growing. How could you cap it at 20 actions, and what does that trade off?
Check my code
redo_stack as in the simulator above. Next task (B2.2.4): a queue for the reservation waitlist, first come, first served.Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Reverse with a stack
Write reverse(text) that pushes every character onto a stack (a list used only with append and pop) and then pops them all to build the reversed string. Do not use slicing or reversed().
Starter file (write your code where it says pass # your code here):
def reverse(text):
pass # your code here
# ---- tests ----
print(reverse("ShelfWise"))
print(reverse("racecar"))
print(repr(reverse("")))
Expected output when your code is correct:
esiWflehS racecar ''
Hint
Model solution
def reverse(text):
stack = []
for ch in text:
stack.append(ch)
out = ""
while stack:
out += stack.pop()
return out
# ---- tests ----
print(reverse("ShelfWise"))
print(reverse("racecar"))
print(repr(reverse("")))
Task 2: Balanced brackets
Write balanced(expr) that returns True if every ( [ { has a matching closing bracket in the right order. Use a stack. Ignore all other characters.
Starter file (write your code where it says pass # your code here):
def balanced(expr):
pass # your code here
# ---- tests ----
for e in ["(a[b]{c})", "([)]", "((x)", "x)", "", "{[()()]}"]:
print(f"{e!r:12} {balanced(e)}")
Expected output when your code is correct:
'(a[b]{c})' True
'([)]' False
'((x)' False
'x)' False
'' True
'{[()()]}' True
Hint
Model solution
def balanced(expr):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in expr:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
# ---- tests ----
for e in ["(a[b]{c})", "([)]", "((x)", "x)", "", "{[()()]}"]:
print(f"{e!r:12} {balanced(e)}")
Task 3: Postfix calculator
In postfix (reverse Polish) notation, "3 4 + 2 *" means (3 + 4) × 2. Write evaluate(expr) using a stack: push numbers; for an operator, pop two values, apply it and push the result. Support + - * /. Raise ValueError with a clear message for too few operands, an unknown token, or leftover values.
Starter file (write your code where it says pass # your code here):
def evaluate(expr):
pass # your code here
# ---- tests ----
print(evaluate("3 4 + 2 *"))
print(evaluate("10 2 8 * + 3 -"))
print(evaluate("7 2 /"))
for bad in ["3 +", "3 4 x", "1 2 3 +"]:
try:
evaluate(bad)
except ValueError as e:
print("error:", e)
Expected output when your code is correct:
14.0 23.0 3.5 error: not enough operands for + error: unknown token x error: leftover values
Hint
Model solution
def evaluate(expr):
stack = []
for token in expr.split():
if token in "+-*/" and len(token) == 1:
if len(stack) < 2:
raise ValueError(f"not enough operands for {token}")
b = stack.pop()
a = stack.pop()
if token == "+": stack.append(a + b)
elif token == "-": stack.append(a - b)
elif token == "*": stack.append(a * b)
else: stack.append(a / b)
else:
try:
stack.append(float(token))
except ValueError:
raise ValueError(f"unknown token {token}")
if len(stack) != 1:
raise ValueError("leftover values")
return stack[0]
# ---- tests ----
print(evaluate("3 4 + 2 *"))
print(evaluate("10 2 8 * + 3 -"))
print(evaluate("7 2 /"))
for bad in ["3 +", "3 4 x", "1 2 3 +"]:
try:
evaluate(bad)
except ValueError as e:
print("error:", e)
Learning objectives
By the end of this page you should be able to:
- Explain what "last in, first out" (LIFO) means and why a stack behaves that way.
- Describe and use the fundamental operations push, pop, peek and isEmpty, and predict the state of a stack after a sequence of operations.
- Explain how stack operations affect performance (constant time) and memory usage, including overflow and underflow in a fixed-size stack.
- Construct a stack in Python with a list, and compare it with a fixed-size array implementation.
- Identify problems for which a stack is appropriate, such as undo, back navigation, bracket matching and the call stack, and justify the choice.
What is a stack?
A stack is an abstract data type in which items are added and removed at one end only, called the top. The last item added is the first one removed: last in, first out (LIFO). Think of a pile of returned books or a stack of plates.
The operations
| Operation | What it does | Python list | Java | Cost |
|---|---|---|---|---|
| push(x) | Add x on top | s.append(x) | stack.push(x) | O(1) |
| pop() | Remove and return the top item | s.pop() | stack.pop() | O(1) |
| peek() | Return the top item without removing it | s[-1] | stack.peek() | O(1) |
| isEmpty() | True if there are no items | len(s) == 0 | stack.isEmpty() | O(1) |
Popping or peeking an empty stack is an error called underflow (Python: IndexError). Always check isEmpty first.
Performance and memory
- All four operations touch only the top, so they take constant time, O(1), however many items the stack holds.
- With a Python list, the top must be the end:
appendandpop()are O(1). Using the front (insert(0, x),pop(0)) would shift every item, O(n). - Fixed-size array + top index (static): memory is reserved up front, so it is predictable but may be wasted, and pushing onto a full stack causes overflow.
- Dynamic (list or linked list): memory grows with the items, so no overflow until memory runs out, but there is resizing or pointer overhead.
- Memory use is proportional to the number of items. An undo history that is never trimmed, or very deep recursion on the call stack, can use a lot of memory; the latter ends in a "stack overflow" (Python: RecursionError).
When is a stack appropriate?
Whenever the most recent item must be dealt with first, or work must be reversed or backtracked:
- Undo in editors and in ShelfWise; the browser Back button.
- Checking matching brackets; evaluating expressions.
- The call stack: each function call is pushed and popped on return (recursion, B2.4.4).
- Backtracking: retracing steps in a maze, or depth-first search.
A stack is not appropriate when items must be served in arrival order (use a queue) or accessed at any position (use a list or array).
Fixed-size array implementation
SIZE = 5
items = [None] * SIZE
top = -1 # index of the top item; -1 means empty
def push(x):
global top
if top == SIZE - 1:
raise OverflowError("stack is full")
top = top + 1
items[top] = x
def pop():
global top
if top == -1:
raise IndexError("stack is empty")
x = items[top]
top = top - 1
return x
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Explain why a stack is described as a LIFO data structure. [2]
2. An empty stack S has these operations applied: push(4), push(7), pop(), push(2), push(9), peek(), pop(). State (a) the values returned by the pop and peek operations in order, (b) the contents of S, bottom to top. [3]
3. Describe the purpose of the isEmpty operation and why it is needed before pop. [2]
4. A stack is implemented with a Python list. Explain why the top of the stack should be the end of the list rather than the start. [3]
5. Compare implementing a stack with a fixed-size array and with a dynamic list, in terms of memory usage. [4]
6. ShelfWise needs an Undo feature for catalogue changes. Explain why a stack is an appropriate data structure for this. [3]