Reputation: 68720
a,b = 0,1
while b < 50:
print(b)
a = b
b = a+b
outputs:
1
2
4
8
16
32
wheras:
a,b = 0,1
while b < 50:
print(b)
a,b = b, a+b
outputs (correct fibonacci sequence):
1
1
2
3
5
8
13
21
34
Aren't they the same? I mean a,b = b, a+b
is essentially the same as a = b
and b = a+b
written separately -- no?
Upvotes: 5
Views: 1456
Reputation: 539
How two assignment operations done in the same time:
a,b = b,a+b
: first in background, I think python assigns a+b
to a variable let us call it x
and assigns b
to a variable let us call it y
then, assigns x
to b
and y
to a
.
I think the concept of "simultaneously" is not true by logic, the value of a
in memory must be changed first, then b
or vice versa, so the value of a
still depends on b
or vice versa unless there is another variables to hold the new values as above.
Upvotes: 0
Reputation: 115630
No, they are not the same.
When you write a,b = b, a+b
, the assignments are done "simultaneously". a,b = b, a+b
is same as (a, b) = (b, a+b)
. So, after
a, b = 5, 8
a=5 and b=8. When Python sees this
(a, b) = (b, a+b)
it first calculates the right side (b, a+b)
which is (8,13)
and then assigns (this tuple) to the left side, to (a,b)
.
When you have: a = b
and then b = a+b
, the two operations are done one after the other. But for every one of them:
a = b
It first calculates the right side b
and then assigns (this value) to the left side, to a
. And again
b = a + b
It first calculates the right side a + b
and then assigns (this value) to the left side, to b
.
Upvotes: 11
Reputation: 3461
The second example represents a tuple being used to perform "simultaneous" assignments.
(A,B)=(B,A+B)
Tuples are immutable, meaning that their contents cannot be changed once set. Also, Python handles assignments from right to left. So when the tuple on the right is created, the values cannot change even though A & B are assigned new values on the left.
Upvotes: 1
Reputation: 70133
For this:
a,b = b, a+b
everything on the right side is evaluated first and then assigned to the left side. So you are using the value of a
on the right side before the assignment of a on the left side changes it.
For this:
a = b
b = a+b
the value of a
is changed before the second statement is executed. So your results are different.
Upvotes: 3
Reputation: 29737
These statements are different.
a = b
b = a+b
modifies a
, and then uses modified value to change b
. Actually, it always does b = b + b
.
a,b = b, a+b
changes b
and a
in the same moment, so b
is calculated using original a
value.
Upvotes: 5
Reputation: 270707
They are not the same. In the first example, a
is assigned the value of b
and then its new value is added to b
. Effectively b + b
.
In the second example, a is assigned the current value of b
and b
is assigned the current value of a
plus the current value of b
. It happens before the value of a
changes.
The two assignments happen simultaneously rather than sequentially.
Upvotes: 5