Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python variable assignment question

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?

like image 809
eozzy Avatar asked Jun 26 '11 16:06

eozzy


1 Answers

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.

like image 52
ypercubeᵀᴹ Avatar answered Oct 10 '22 09:10

ypercubeᵀᴹ