Python a, b = b, a +b
Let's say we start with a
and b
like this:
a = 2
b = 3
So, when you do:
a, b = b, a + b
what happens is you create the tuple (b, a + b)
or (3, 5)
and then unpack it into a
and b
so a
becomes 3
and b
becomes 5
.
In your second example:
a = b
# a is now 3
b = a + b
# b is 3 + 3, or 6.
The line:
a, b = b, a + b
is closer to:
temp_a = a
a = b
b = temp_a + b
where b
is using the old value of a
before a
was reassigned to the value of b
.
Python first evaluates the right-hand expression and stores the results on the stack, then takes those two values and assigns them to a
and b
. That means that a + b
is calculated before a
is changed.
See How does swapping of members in the python tuples (a,b)=(b,a) work internally? for the low-down on how this all works, at the bytecode level.
Let's grok it.
a, b = b, a + b
It's a tuple assignment, means (a, b) = (b, a + b)
, just like (a, b) = (b, a)
Start from a quick example:
a, b = 0, 1
#equivalent to
(a, b) = (0, 1)
#implement as
a = 0
b = 1
When comes to (a, b) = (b, a + b)
EAFP, have a try directly
a, b = 0, 1
a = b #a=b=1
b = a + b #b=1+1
#output
In [87]: a
Out[87]: 1
In [88]: b
Out[88]: 2
However,
In [93]: a, b = b, a+b
In [94]: a
Out[94]: 3
In [95]: b
Out[95]: 5
The result is different from the first try.
Tha's because Python firstly evaluates the right-hand a+b
So it equivalent to:
old_a = a
old_b = b
c = old_a + old_b
a = old_b
b = c
In summary, a, b = b, a+b
means,a
exchanges to get old_value of b
,b
exchanges to get the sum of old value a
and old value b
,
In a, b = b, a + b
, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to:
c = a + b
a = b
b = c
In the second example, the value of a
has already been changed by the time b = a + b
is run. Hence, the result is different.