Stacks

intermediate20 min

Learning objectives

  • Explain LIFO processing
  • Perform push and pop operations
  • Compare stacks with queues
  • Apply stack operations to practical computing problems

Learn

AQA 4.2.6 — Stacks (LIFO)

Retrieval: the previous lesson defined an ADT as an interface separate from its implementation - a stack is exactly that: a specific, named ADT with its own fixed interface (push, pop, peek, is_empty).

A stack follows Last-In, First-Out (LIFO): the most recently added item is the first one removed — like a stack of plates.

OperationMeaning
pushadd an item to the top
popremove and return the top item
peeklook at the top item without removing it
is_emptycheck whether the stack has any items

Implementing a stack in Python

A Python list gives you a stack for free, using append for push and pop for pop:

stack = []
stack.append("Page 1")   # push
stack.append("Page 2")   # push
stack.append("Page 3")   # push

print(stack.pop())        # "Page 3" - LIFO: last one out first
print(stack.pop())        # "Page 2"

Worked example — a browser history simulator

history = []

def visit(url):
    history.append(url)
    print(f"Visited: {url}")

def go_back():
    if history:
        current = history.pop()
        print(f"Left: {current}")
    else:
        print("No history to go back to.")

visit("home")
visit("search")
visit("results")
go_back()   # Left: results
go_back()   # Left: search

Common mistake

Calling .pop() on an empty stack raises an error rather than returning something harmless like None - always check is_empty (or, in Python, check the list is truthy) before popping, exactly as go_back() does above with if history:.

Why stacks matter beyond this lesson

Stacks aren't just an isolated topic — they're the mechanism your computer actually uses to manage function calls (the call stack), which you'll meet formally in Sequence 10 (Advanced Programming Techniques, Year 13) when you study stack frames and recursion.

Challenge

Trace, step by step, what the history list contains after: visit("a"), visit("b"), go_back(), visit("c"), go_back(), go_back().

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab

Test yourself

Check your understanding with exam-style questions.

Go to Exam Practice
Log in to track this lesson on your progress dashboard.
Log in