This is my first question and I started to learn Python. Is there a difference between:
a, b = b, a + b
and
a = b
b = a +
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.
I hope that you haven't been influenced by C language, which the priority of assignment operator =
is higher than that of Comma operator ,
. Do not think it's (a), (b = b), (a + b)
. It's a tuple assignment, meaning it's (a, b) = (b, a + b)
.
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
,
a, b = b, a + b
is similar to a, b = 0, 1
assigning values to both variables a, b
at same time. First assign a = b
and then b = a + b
.
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.
There are differences between a,b = b,a+b and a=b b=a+b
let's have a look at the following two examples:
eg1:
a,b = 0,1
while a<10:
print(a)
a,b = b,a+b
#output:
0
1
1
2
3
5
8
eg2:
a,b = 0,1
while a<10:
print(a)
a=b
b=a+b
#output:
0
1
2
4
8
This is because the interpreter always calculates the figures in the right side of the Equals sign first. The calculation results will be assigned to the variables which on the left hand side only if all the calculation has been done on the right hand side.