4

I have found example for Fibonacci sequence that goes like this:

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

fib(20)

So here's what I don't get it:

a, b = 0, 1 # is just a shortcut for writing
a = 0
b = 1

right?

Now, following the same logic

a, b = b, a+b #should be the same as writing
a = b
b = a+b

But it isn't because if I write it like that, the output is different. I'm having some hard time understanding why. Any thoughts?

That1Guy
  • 7,075
  • 4
  • 47
  • 59
Rokke
  • 41
  • 3

3 Answers3

3

Yes It isn't exactly the same , because when you write -

a, b = b, a+b

The value of a and b at the time of executing the statement is considered, lets say before this statement, a=1 , b=2 , then first right hand side is calculated , so b=2 is calculated and a+b=3 is calculated. Then the assignment occurs, that is a is assigned value 2 and b is assigned value 3.

But when you write -

a = b
b = a+b

The assignment occurs along with calculation, that is first b=2 is calculated, then assigned to a , so a becomes 2 , then a+b is calculated (with the changed value of a) , so a+b=4 and it is assigned to b , so b becomes 4 , and hence the difference.

a,b = b, a

This is a shorthand for swapping values of a and b , please note that if you want to swap the values without using this notation, you would need a temporary variable.

Internally how it works is that the right hand sid is made into a tuple, and then the values are unpacked, a simple test to see this is -

>>> a = 5
>>> b = 10
>>> t = a, b
>>> t
(5, 10)
>>> b, a = t
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

a, b = c, d is not shorthand for the following:

a = c
b = d

It's actually shorthand for this:

a, b = (c, d)

I.e., you're creating a tuple (c, d), a tuple with the values of c and d, which is then unpacked into the target list a, b. The tuple with its values is created before the values are unpacked into the target list. It actually is one atomic* operation, not a shorthand for several operations. So it does not matter whether one of the variables in the target list also occurs on the right hand side of the assignment operation.

* Not "atomic" in the sense of database ACID, but still not separate statements.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

It is not the same thing.

x, y = y, x

equals to:

t = x
x = y
y = t

It actually uses a temporary variable to swap x and y.

So back to a, b = b, a+b. This expression equals to:

m = a; n = b

a = n

b = m + n

Community
  • 1
  • 1
Will
  • 792
  • 1
  • 5
  • 22