0
x = 1
y = 2

x, y = y, x + y
print(x, y)

The above piece prints me: 2, 3

The Python documentation and previous stackoverflow question answers regarding this topic tells that assignment goes from right to left.

So in my case y = x + y goes first -> y = 3, then x = y goes second -> x = 3, and the output should be: 3, 3

If assignment goes from left-to-right, then the resulting output should be: 2, 4

So both left-to-right and right-to-left doesn't work here, seems like it is done simultaneously. My interpreter version is 3.8

Help me please. Thanks!

BatyaGG
  • 674
  • 1
  • 7
  • 19

1 Answers1

1

The right hand side of the assignment is computed all before the assignment happens.

So first you compute (y, x+y) which is (2, 3) and then you unpack it into x and y.

See also what happens if on the left you have more than identifiers but also expressions:

>>> a = [1, 2]
>>> i = 1
>>> a[i], i = 3, 4
>>> a, i
([1, 3], 4)
Francis Colas
  • 3,459
  • 2
  • 26
  • 31