Python - Multiple Assignment

835 views Asked by At

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.

3

There are 3 answers

0
ekl1pse On BEST ANSWER
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.

1
KKJ On

In a multiple assignment, the right side is always computed first.

In effect,

a, b = b, a + b

is the same as:

b = a + b
a = b
2
Ananda On

When you do a, b = d, e the order in which assignment happens in from right to left. That is, b is first given the value of e and then the other assignment happens. So when you do a, b = b, a + b what you are effectively writing is,

 b = a + b
 a = b

Hence the difference.

You can verify this by doing

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

the first output is 1 1. So first b becomes 0+1 and then a is given the value of b=a making it also 1.

If you want more details on how this works, you can check out this question.