Home › Theme B › B2 › B2.2 › B2.2.3

B2.2.3 Stacks: last in, first out

SL + HLCommand term: Explain

1. 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.

Implementation: Python list (dynamic)Fixed array, size 5, with top index
Code: -
Returns: -
Push some books.

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.

Catalogue:
Try: add Matilda, delete Emma, add Kim, then Undo three times.

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: trace the stack

A new sequence each time. What is the answer?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 2, task 3. Librarians make mistakes. Give ShelfWise an Undo button: write the four stack operations on a Python list, then use them to record and reverse catalogue actions.

Expected output

['Dune', 'Holes', 'Kim'] ['add', 'Kim'] ['Dune', 'Holes', 'Emma'] 1 Nothing to undo ['Dune', 'Emma'] True

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

    Extension: add a 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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    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):

    File: b2_2_3_average.py
    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
    Last in, first out: the last character pushed is the first popped.
    Model solution
    File: b2_2_3_average_solution.py
    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("")))
    
    Moderate

    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):

    File: b2_2_3_moderate.py
    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
    On a closing bracket, the top of the stack must be the matching opening bracket.
    Model solution
    File: b2_2_3_moderate_solution.py
    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)}")
    
    Challenging

    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):

    File: b2_2_3_challenging.py
    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
    The first value popped is the right-hand operand: for '7 2 /', b = 2 and a = 7.
    Model solution
    File: b2_2_3_challenging_solution.py
    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:

    1. Explain what "last in, first out" (LIFO) means and why a stack behaves that way.
    2. Describe and use the fundamental operations push, pop, peek and isEmpty, and predict the state of a stack after a sequence of operations.
    3. Explain how stack operations affect performance (constant time) and memory usage, including overflow and underflow in a fixed-size stack.
    4. Construct a stack in Python with a list, and compare it with a fixed-size array implementation.
    5. 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

    OperationWhat it doesPython listJavaCost
    push(x)Add x on tops.append(x)stack.push(x)O(1)
    pop()Remove and return the top items.pop()stack.pop()O(1)
    peek()Return the top item without removing its[-1]stack.peek()O(1)
    isEmpty()True if there are no itemslen(s) == 0stack.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: append and pop() 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]

    Items are added and removed at the same end only, the top [1]; so the last item pushed is the first one popped / last in, first out [1].

    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]

    (a) pop returns 7 [1]; peek returns 9, then pop returns 9 [1]. (b) S contains 4, 2 (2 on top) [1].

    3. Describe the purpose of the isEmpty operation and why it is needed before pop. [2]

    isEmpty returns true if the stack holds no items [1]; checking it before pop prevents stack underflow / a runtime error from removing from an empty stack [1].

    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]

    append and pop() at the end take constant time / O(1) [1]; inserting or removing at the start (insert(0, x), pop(0)) requires every other element to shift [1], which takes O(n) time and gets slower as the stack grows [1].

    5. Compare implementing a stack with a fixed-size array and with a dynamic list, in terms of memory usage. [4]

    Both give O(1) push and pop / store items in order [1]. Fixed array: memory is allocated in advance, so unused slots waste memory [1] and pushing onto a full array causes overflow [1]. Dynamic list: memory grows and shrinks with the number of items, so it cannot overflow until memory is exhausted, but has overhead from resizing / spare capacity / pointers [1].

    6. ShelfWise needs an Undo feature for catalogue changes. Explain why a stack is an appropriate data structure for this. [3]

    Each change is pushed onto the stack as it happens [1]; undo must reverse the most recent change first, which is the item on top [1]; repeated pops reverse changes in the opposite order to which they were made, exactly matching LIFO behaviour [1].