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.
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
ianda[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: