I have recently started learning python. I was playing around with simultaneous assignments today and came across some results that were produced by my code that I cannot understand.
x, y = 3, 5
x, y = y, (x+y)
print(y)
The output is 8.
I am not understanding why y = 8
instead of y = 10
despite x = y = 5
being evaluated first. Since y = 8
, this tell us that x = 3
when y = x + y
is being evaluated ? How is that possible if x = y
is first evaluated, since it is evaluated left to right ?
I first debugged the code (which produced the same result), which I cannot understand. I also have tried looking at the python documentation, where it states "simultaneous overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion." The example that it presents follows my logic:
x = [0, 1]
i = 0
i, x[i] = 1, 2
print(x)
It outputs 2.
(Evaluated left to right) Since i is updated to 1. Then, this updated i is used and hence, x[1] = 2
not x[0] = 2
.
I really would appreciate some help.