The confusion of assigning multiple Python variables

My first day in Python and get confused with a very brief example. Hope someone can give some explanation why there is some difference between these several versions. You are welcome!

V1: output 1, 1, 2, 3, 5, 8

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

V2: output 1, 2, 4, 8

 a, b = 0, 1 while b < 10: print(b) a = b b = a+b 
+5
source share
1 answer

In the first version, the right hand is evaluated first, so b does not increase when added.

To run the first version for iterating over a pair:

1.

 a = 0 b = 1 a, b = 1, 1 # b is 1, and a is 0 

2.

 a = 1 b = 1 a, b = 1, 2 # b is 1 and a is 1 

3.

 a = 1 b = 2 a, b = 2, 3 # b is 2 and a is 1 

In the second version, b is assigned before it is added, so this is how the second version goes:

1.

 a = 0 b = 1 a = b # a is now 1. b = a + b # b is now 2, because both a and b are 1. 

2.

 a = 1 b = 2 a = b # a is now 2. b = a + b # b is now 4, because both a and b are 2. 
+5
source

Source: https://habr.com/ru/post/1259286/


All Articles