Consider the following Python3 program:
a = [0, 0]
i = 0
a[i] = i = 1
print(a, i)
a = [0, 0]
i = 0
i = a[i] = 1
print(a, i)
I expected the output to be:
[0, 1] 1
[1, 0] 1
But instead I got:
[1, 0] 1
[0, 1] 1
My question is: is there anything in the Python language specification about associativity of the assignment operator, or is the behavior for the above example undefined?
All I was able to find is that expressions are evaluated form left to right, except that r-value is evaluated first in case of assignment, but that doesn't help.
Right-associative operators of the same precedence are evaluated in order from right to left. For example, assignment is right-associative.
Associativity of Python Operators Associativity is the order in which an expression is evaluated that has multiple operators of the same precedence. Almost all the operators have left-to-right associativity. For example, multiplication and floor division have the same precedence.
Any assignment operators are typically right-associative. To prevent cases where operands would be associated with two operators, or no operator at all, operators with the same precedence must have the same associativity.
The assignment operator has left-to-right-to-left associativity, which means that the value of the expression to the left of the assignment operator is evaluated first and that the result is assigned to the operand on the right. A string variable can hold digits such as phone numbers and zip codes.
Short answer: the code is well defined; the order is left-to-right.
Long answer:
First of all, let's get the terminology right. Unlike in some other languages, assignment in Python is a statement, not an operator. This means that you can't use assignment as part of another expression: for example i = (j = 0)
is not valid Python code.
The assignment statement is defined to explicitly permit multiple assignment targets (in your example, these are i
and a[i]
). Each target can be a list, but let's leave that aside.
Where there are multiple assignment targets, the value is assigned from left to right. To quote the documentation:
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
Just to make it clear, since I struggled myself to understand this. The statement:
a = b = c = ... = E
is equivalent to
a = E
b = E
c = E
...
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