A stack follows last in, first out. push adds a new item, pop removes the latest item and peek reads it without removing it. Trace the stack contents after a sequence of mixed operations.
Watch out: Calling pop on an empty stack raises an error unless you first check for underflow.
Study this example, identify inputs and outputs, then trace the key variables. Run and adapt it in Python 3.
class Stack:
def __init__(self): self.items = []
def push(self, value): self.items.append(value)
def pop(self):
if not self.items: raise IndexError("stack underflow")
return self.items.pop()
def peek(self):
if not self.items: raise IndexError("stack empty")
return self.items[-1]
s = Stack()
s.push('A'); s.push('B')
2 · Independent programming challenge
Implement push, pop and peek using a list, including underflow handling. Download the starter, design your solution, and add tests before revealing the answer.
Stretch task: investigate time/space complexity or data validation, then write an evaluation of your approach.
Show reference solution after attempting the task
class Stack:
def __init__(self): self.items = []
def push(self, value): self.items.append(value)
def pop(self):
if not self.items: raise IndexError("stack underflow")
return self.items.pop()
def peek(self):
if not self.items: raise IndexError("stack empty")
return self.items[-1]
s = Stack()
s.push('A'); s.push('B')
assert s.peek() == 'B' and s.pop() == 'B' and s.pop() == 'A'
print('Stack tests passed')
3 · Debug and explain
Change one boundary condition in the starter or reference program. Predict which test fails, then repair it and document why.
Concept check: Which item is removed first after pushing A then B?
Reveal explanation
B, because a stack follows last in, first out (LIFO).
4 · Assess your learning
Describe the algorithm or design in your own words; include a normal test, a boundary test and an invalid input. Compare your answers with the reference solution and record one improvement.
Trace stack operations vertically, marking the top after every push or pop. Explain why LIFO makes stacks useful for undo actions, call stacks and expression evaluation.
Quick check: Which item is removed first after pushing A, B and C?
Check: C, because the last item added is the first removed.