pythonvariable-assignmentmultiple-assignment

Python - Multiple Assignment


Recently I was reading through the official Python documentation when I came across the example on how to code the Fibonacci series as follows:

a, b = 0, 1 
while a < 10:
 print (a)
 a, b = b, a + b

which outputs to 0,1,1,2,3,5,8

Since I've never used multiple assignment myself, I decided to hop into Visual Studio to figure out how it worked. I noticed that if I changed the notation to...

a = 0
b = 1
while a < 10:
 print (a) 
 a, b = b, a + b

... the output remains the same.

However, if I change the notation to...

a = 0
b = 1
while a < 10:
 print(a)
 a = b
 b = a + b

... the output changes to 0, 1, 2, 4, 8

The way I understand multiple assignments is that it shrinks what can be done into two lines into one. But obviously, this reasoning must be flawed if I can't apply this logic to the variables under the print(a) command.

It would be much appreciated if someone could explain why this is/what is wrong with my reasoning.


Solution

  • a = 0
    b = 1
    while a < 10:
     print(a)
     a = b
     b = a + b
    

    In this case, a becomes b and then b becomes the changed a + b

    a, b = 0, 1 
    while a < 10:
     print (a)
     a, b = b, a+b
    

    In this case, a becomes b and at the same time b becomes the original a + b.

    That's why, in your case b becomes the new a + b, which, since a = b, basically means b = b + b. That's why the value of b doubles everytime.