A-level Python · Lesson 3 of 9

Stacks and LIFO

OCR H446 data structures / AQA 7517 data structures

Implement push, pop and peek using a list, including underflow handling.

← All A-level Python lessons

Building a stack

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.

1 · Learn and explore

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.

Download starter + solution ZIP ↓

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.

Progress is stored only in this browser.

Want extra practice? Try interactive Python tracing and debugging questions →