Python stacks and balanced parentheses

A stack removes the most recently added item first. Opening parentheses are pushed; a closing parenthesis must match an existing opening one.

Python
def balanced(text):
    stack = []
    for char in text:
        if char == "(":
            stack.append(char)
        elif char == ")":
            if not stack:
                return False
            stack.pop()
    return not stack

print(balanced("(())"))
print(balanced(")("))
assert balanced("")
assert not balanced("(()")
Read the full lesson