2

I'm kind of beginner in python. I was looking at one the types to make a fibonacci function,

def fib(n):
a=0
b=1
while a<n:
    print a
    a,b=b,a+b

and I saw the a,b=b,a+b declaration. So, I thought a=b and b=a+b were the same to a,b=a,b+a, so I changed the function for it to be like this:

def fib(n):
a=0
b=1
while a<n:
    print a
    a=b
    b=a+b

and I thought it would be right, but when I executed the program, I got a different output. Can someone explain to me the difference between those two types of declaration?

Thanks, anyway.

4 Answers4

1

b, a+b creates a tuple containing those two values. Then a, b = ... unpacks the tuple and assigns its values to the variables. In your code however you overwrite the value of a first, so the second line uses the new value.

a, b = b, a + b

is roughly equal to:

tmp = a
a = b
b = tmp + b
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

When Python executes

a,b = b, a+b

it evaluates the right-hand side first, then unpacks the tuple and assigns the values to a and b. Notice that a+b on the right-hand side is using the old values for a.

When Python executes

a=b
b=a+b

it evaluates b and assigns its value to a. Then it evaluates a+b and assigns that value to b. Notice now that a+b is using the new value for a.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

That syntax simultaneously assigns new values to a and b based on the current values. The reason it's not equivalent is that when you write the two separate statements, the second assignment uses the new value of a instead of the old value of a.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
0

In the first example, a isn't updated to take the value of b until the entire line has been evaluated -- so b is actually a + b.

In you example, you've already set a to b, so the last line (b=a+b) could just as easily be b=b+b.

It's all in the order in which things are evaluated.

jbsmith
  • 1,616
  • 13
  • 10