Search code examples
pythonoperators

Python assignment operator associativity


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.


Solution

  • 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.