The order in which a+b
is calculated changes.
In the first case, a+b
is calculated after a=b
is executed.
In the second case, a+b
is calculated before any assignment happens.
In general, what happens in Python is that things at the right of =
are evaluated before the assignment happens.
If you're curious, you can take a look of what's happening behind the scenes using dis
, that will show you the bytecode:
>>> dis.dis('a, b = b, a+b')
1 0 LOAD_NAME 0 (b) # Push the value of 'b' on top of the stack
2 LOAD_NAME 1 (a) # Push the value of 'a'
4 LOAD_NAME 0 (b) # Push the value of 'b'
6 BINARY_ADD # Compute the sum of the last two values on the stack
# Now the stack contains the value of 'b' and of 'a+b', in this order
8 ROT_TWO # Swap the two values on top of the stack
# Now the stack contains the value of 'a+b' and of 'b', in this order
10 STORE_NAME 1 (a) # Store the value on top of the stack inside 'a'
12 STORE_NAME 0 (b) # Store the value on top of the stack inside 'b'