How to Evaluate RPN Expressions in Python

Use a stack to evaluate Reverse Polish Notation token lists with a dictionary of operator lambdas, truncating division toward zero.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

22 lines
Python 3.9+
def eval_rpn(tokens):
    stack = []
    ops = {
        '+': lambda a, b: a + b,
        '-': lambda a, b: a - b,
        '*': lambda a, b: a * b,
        '/': lambda a, b: int(a / b)  # truncate toward zero
    }
    for token in tokens:
        if token in ops:
            b = stack.pop()
            a = stack.pop()
            stack.append(ops[token](a, b))
        else:
            stack.append(int(token))
    return stack[0]

if __name__ == "__main__":
    # Example: "3 4 + 2 * 7 /" → ((3+4)*2)/7 = 2
    expression = ["3", "4", "+", "2", "*", "7", "/"]
    result = eval_rpn(expression)
    print(f"Result of {expression} = {result}")

Output

stdout
Result of ['3', '4', '+', '2', '*', '7', '/'] = 2

How it works

A stack holds operands as tokens are scanned; when an operator appears, the top two values are popped and the result is pushed. The ops dictionary maps each operator symbol to a lambda that computes the result, and integer division uses int(a / b) for Python-style truncation like many calculators. This approach gives O(n) time and O(n) space. At the end, the single remaining stack value is the expression's result.

Common mistakes

  • Forgetting that operand order matters: the first popped value is `b`, not `a`
  • Using `//` for division, which floors toward negative infinity instead of truncating toward zero
  • Not converting string tokens to `int` before pushing them
  • Assuming division returns a float when truncation toward zero is expected

Variations

  1. Swap the lambda for a `match` statement in Python 3.10+
  2. Use a list-based stack with a helper function for each operator instead of lambdas

Real-world use cases

  • Implementing calculators and expression parsers in trading platforms that need deterministic operator ordering.
  • Building custom scripting engines where user input is pre-tokenized into postfix notation for simple evaluation.
  • Evaluating formula strings in spreadsheet-like tools that convert input to RPN to avoid precedence bugs.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.