Everybody knows that in Python assignments do not return a value, presumably to avoid assignments on if
statements when usually just a comparison is intended:
>>> if a = b:
File "<stdin>", line 1
if a = b:
^
SyntaxError: invalid syntax
>>> if a == b:
... pass
...
For the same reason, one could suspect that multiple assignments on the same statement were also syntax errors.
In fact, a = (b = 2)
is not a valid expression:
>>> a = (b = 2)
File "<stdin>", line 1
a = (b = 2)
^
SyntaxError: invalid syntax
So, my question is: why a = b = 2
works in Python as it works in other languages where assignment statements have a value, like C?
>>> a = b = c = 2
>>> a, b, c
(2, 2, 2)
Is this behavior documented? I could not found anything about this in the assignment statement documentation: http://docs.python.org/reference/simple_stmts.html#assignment-statements
The value of an assignment expression is the value of the right-side operand. As a side effect, the = operator assigns the value on the right to the variable or property on the left so that future references to the variable or property evaluate to the value.
The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.
An assignment statement sets the current value of a variable, field, parameter, or element. The statement consists of an assignment target followed by the assignment operator and an expression. When the statement is executed, the expression is evaluated and the resulting value is stored in the target.
In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the assignment statement (or expression) is a fundamental construct.
It's right there in the syntax:
assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
The tiny +
at the end of (target_list "=")+
means "one or more". So the line a = b = c = 2
does not consist of 3 assignment statements, but of a single assignment statement with 3 target lists.
Each target list in turn consist only of a single target (an identifier in this case).
It's also in the text (emphasis mine):
An assignment statement [...] assigns the single resulting object to each of the target lists, from left to right.
This can lead to interesting results:
>>> (a,b) = c = (1,2)
>>> (a, b, c)
(1, 2, (1, 2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With