Data Structures18 min read

Stack in Python

Learn stack (LIFO) using lists and deque, why stacks matter, and real examples like undo operations and bracket matching.

David Miller
November 15, 2025
3.0k83

A stack follows LIFO:
Last In, First Out.

Real examples:

  • undo/redo
  • browser back button
  • function call stack

Implement stack with list (simple)

stack = []
stack.append("A")  # push
stack.append("B")
print(stack)

top = stack.pop()  # pop
print(top)
print(stack)

Stack example: bracket matching

Goal: check if parentheses are balanced.

def is_balanced(s: str) -> bool:
    stack = []
    pairs = {")": "(", "]": "[", "}": "{"}

    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in ")]}":
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()

    return len(stack) == 0

print(is_balanced("(a[b]{c})"))  # True
print(is_balanced("(a[b]{c}"))   # False

Graph: stack LIFO

flowchart TD
  A[Push A] --> B[Stack: A]
  B --> C[Push B]
  C --> D[Stack: A,B]
  D --> E[Pop -> B]

Remember

  • stack = append + pop
  • stack[-1] is the top
  • used in parsing and “undo” logic
#Python#Intermediate#Stack