TheAlgorithms/Python · error · IndexError

list index out of range

Error message

list index out of range

What it means

Explicitly raised in the loop of infix_to_postfix() inside data_structures/stacks/infix_to_prefix_conversion.py:93 when a ')' is scanned while the operator stack is empty — a close bracket with no possible matching open bracket. The message intentionally mimics CPython's builtin IndexError text, but this is a manual raise, not an accidental list access. Note the function also prints a tabular trace, so partial output precedes the raise.

Source

Thrown at data_structures/stacks/infix_to_prefix_conversion.py:93

    print_width = max(len(infix), 7)

    # Print table header for output
    print(
        "Symbol".center(8),
        "Stack".center(print_width),
        "Postfix".center(print_width),
        sep=" | ",
    )
    print("-" * (print_width * 3 + 7))

    for x in infix:
        if x.isalpha() or x.isdigit():
            post_fix.append(x)  # if x is Alphabet / Digit, add it to Postfix
        elif x == "(":
            stack.append(x)  # if x is "(" push to Stack
        elif x == ")":  # if x is ")" pop stack until "(" is encountered
            if len(stack) == 0:  # close bracket without open bracket
                raise IndexError("list index out of range")

            while stack[-1] != "(":
                post_fix.append(stack.pop())  # Pop stack & add the content to Postfix
            stack.pop()
        elif len(stack) == 0:
            stack.append(x)  # If stack is empty, push x to stack
        else:  # while priority of x is not > priority of element in the stack
            while stack and stack[-1] != "(" and priority[x] <= priority[stack[-1]]:
                post_fix.append(stack.pop())  # pop stack & add to Postfix
            stack.append(x)  # push x to stack

        print(
            x.center(8),
            ("".join(stack)).ljust(print_width),
            ("".join(post_fix)).ljust(print_width),
            sep=" | ",
        )  # Output in tabular format

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pre-validate with balanced_parentheses() from infix_to_postfix_conversion before calling this function
  2. Strip/repair stray ')' characters in the input pipeline
  3. Catch IndexError (or ValueError for the sibling 'invalid expression' error) around the call and report the expression as malformed

Example fix

// before
result = infix_to_postfix(')1+2')  # IndexError

# after
from data_structures.stacks.infix_to_postfix_conversion import balanced_parentheses
if not balanced_parentheses(expr):
    raise ValueError(f'unbalanced expression: {expr!r}')
result = infix_to_postfix(expr)
Defensive patterns

Strategy: validation

Validate before calling

from data_structures.stacks.infix_to_postfix_conversion import balanced_parentheses
if not balanced_parentheses(expr):
    raise ValueError(f'malformed expression: {expr!r}')
result = infix_to_postfix(expr)

Try / catch

try:
    result = infix_to_postfix(expr)
except (IndexError, ValueError):
    # this converter lacks a pre-check; both errors mean unbalanced parens
    return None

Prevention

When it happens

Trigger: Calling the conversion with an expression like ')1+2' or '1+2)' where a ')' appears before any '(' has been pushed. Only a ')' with a completely empty stack triggers it; a ')' with operators on the stack pops normally.

Common situations: Feeding unvalidated user input or truncated strings to the prefix converter; unlike infix_to_postfix_conversion.py, this variant does NOT pre-check balanced parentheses, so unbalanced input reaches the loop.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/96ed916e082b9ba4. Report an issue: GitHub.