Thuta Learning
IntermediateProgrammingintermediate

Stacks — Last In, First Out

What you'll walk away with

  • Explain the core ideas behind Stacks — Last In, First Out
  • Run the sample Python code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

A stack is one of the simplest data structures and yet remarkably powerful: elements come out (pop) in the exact reverse order they went in (push) — Last In, First Out (LIFO). A precise mental model is a stack of plates: you can only take the top one off, never reach underneath for one lower down. That single constraint is what makes both push and pop O(1) — you only ever touch the end of the underlying storage, so nothing needs to shift. Stacks show up wherever a problem needs 'reverse of arrival order' logic: undo history (only the most recent action can be undone next), the function call stack (a function only resumes after whatever it called has finished), and bracket/parenthesis matching, where a closing bracket must pair with the nearest still-open one — which is exactly the mechanism this lesson's code implements.

Connect it to a real scenario

The Tutorial Platform's content editor can use a stack to verify a lesson author's code snippet has correctly matched brackets before publishing, auto-catching syntax errors. The editor's undo/redo feature can be built the same way, storing action history on a stack.

Try the working example

python
def is_balanced(expression):
    stack = []
    pairs = {")": "(", "]": "[", "}": "{"}
    for char in expression:
        if char in "([{":
            stack.append(char)  # push - O(1)
        elif char in ")]}":
            if not stack or stack.pop() != pairs[char]:  # pop - O(1)
                return False
    return not stack  # everything must have been matched and closed

tests = ["(a[b]{c})", "(a[b)c]", "((("]
for t in tests:
    print(t, "->", is_balanced(t))
You should see
Prints True, False, False for the three test strings, matching whether each string's brackets are correctly balanced.

5-minute try-it

Modify is_balanced so it also returns the index position where the first mismatch occurred, not just True/False.

One important caution

Forgetting to check that the stack is empty after the loop — an unclosed bracket like "(a" would falsely be reported as balanced

Calling stack.pop() without first checking the stack isn't empty — a string like ")a)" raises an IndexError instead of correctly returning False

Wikipedia — Stack (abstract data type)Data Structures & Algorithms

Easy traps

  • Forgetting to check that the stack is empty after the loop — an unclosed bracket like "(a" would falsely be reported as balanced
  • Calling stack.pop() without first checking the stack isn't empty — a string like ")a)" raises an IndexError instead of correctly returning False
  • Validate sample code in a local or test environment before applying it to a production system.

Exercise

Modify is_balanced so it also returns the index position where the first mismatch occurred, not just True/False.

You'll know it worked when: Prints True, False, False for the three test strings, matching whether each string's brackets are correctly balanced.

Stacks — Last In, First Out | Thuta Learning