Skip to content

SyntaxError: invalid syntax with walrus operator

Quick summary

You used the walrus operator := in a context Python does not support, or on Python 3.7 or earlier where it is not available.

Why this happens

  • You are running Python 3.7 or earlier where the walrus operator := is not supported

  • The walrus operator is used in a context that requires parentheses but they are missing

  • You used := in a position where Python expects a statement, not an expression (like at top level)

Minimal example

✗ Broken code
# Python 3.7 or missing parens
if n := len(data) > 10:  # SyntaxError
    print(n)
✓ Fixed code
# Python 3.8+ with parentheses
if (n := len(data)) > 10:
    print(n)  # n is the length, comparison is correct

Parentheses ensure the walrus assignment binds to len(data) and the comparison > 10 applies to the result, not to the assignment itself.

How to diagnose

  • Check the Python version with python --version — the walrus operator requires Python 3.8+

  • Wrap the walrus expression in parentheses if it is used inside a condition or comprehension

  • Ensure the walrus operator is used in an expression context, not as a standalone statement

How to fix

  • Upgrade to Python 3.8+ if you need the walrus operator, or rewrite using traditional assignment

  • Add parentheses around the walrus expression: if (match := pattern.search(text)) is not None

  • Replace := with a separate assignment statement and use the variable in the subsequent expression

How to prevent

  • Check the minimum Python version of your project before using walrus operator features

  • Use parentheses around walrus expressions in conditions and comprehensions to avoid ambiguity

Related Resources

Related Glossary

Related Lessons

← Back to language