Stacks

Last in, first out — undo, matching brackets, the call stack.

A stack is last-in, first-out (LIFO). append pushes. pop from the end pops. The call stack in recursion is the same idea.

Goal

Push cities, pop them, and check matching brackets with a stack.

Push and pop

stack = []
for city in ["Nairobi", "Mombasa", "Kisumu"]:
    stack.append(city)
    print("push", stack)
print("pop", stack.pop())
print("left", stack)

Kisumu came off first — last in, first out.

Matching brackets

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

print(balanced("(a + [b])"))
print(balanced("(a + [b)"))
print(balanced(")("))
Tip

Undo history, nested calls, and bracket matching are stack problems. If you need the oldest item first, that is a queue — next chapter.