SyntaxError
SyntaxError: cannot use assignment expressions with tuple
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
(a, b) := (1, 2) # cannot use with tuple unpacking
SyntaxError: cannot use assignment expressions with tupleWhat causes this error
The walrus operator (:=) was used in a context where it is not allowed — in tuple unpacking, augmented assignment, attribute assignment, or at the statement level.
How to fix it
Use the walrus operator only in valid contexts: while loops, if conditions, and comprehension filters. For other cases, use regular assignment. Wrap the walrus expression in parentheses if needed.
Code that causes this error
(a, b) := (1, 2) # cannot use with tuple unpacking
Fixed code
a, b = (1, 2) # regular unpacking
# Walrus operator in valid context:
while (line := input("> ")) != "quit":
print(line)About SyntaxError
This SyntaxError relates to the walrus operator (`:=`), introduced in Python 3.8 via PEP 572. The walrus operator allows assignment within expressions, but it has specific restrictions. It cannot be used at the top level of an expression statement (use regular assignment), cannot be combined with augmented assignment (no `x := x + 1`), cannot be used in tuple or list unpacking, and cannot assign to attributes or subscripts.
The most common error is trying to use `:=` in a context where it is not syntactically valid or where its precedence causes unexpected parsing. The walrus operator is most useful in while loops with input (`while (line := input()) != 'quit'`) and in comprehension filters (`[y for x in data if (y := f(x)) > 0]`).
Common scenarios
Writing code with missing colons, parentheses, or brackets
Mixing Python 2 and Python 3 syntax when upgrading a codebase
Copy-pasting code from the web with formatting issues or invisible characters
Using reserved keywords as variable or function names